1

I am saving Current Date time as Timestamp with below code in my Android

 userValues.put("rTime",  ServerValue.TIMESTAMP);

Now I want to calculate difference as

String posttime=1576917051506 //retrieve saved timestamp String currenttime=ServerValue.TIMESTAMP //current time difference=1hour 25 minutes

how can i achieve this

Mithu
  • 665
  • 1
  • 8
  • 38
  • This has bern asked and answered before. What did your search turn up? – Ole V.V. Dec 21 '19 at 11:22
  • apologize i did not find any regarding timestamp in android – Mithu Dec 21 '19 at 11:24
  • 1
    I worte [this modern answer](https://stackoverflow.com/a/56413601/5772882) for Android. You may also use [this answer](https://stackoverflow.com/a/23176621/5772882). To use it on Android if your API level happens to be 25 or lower, you need to add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your project, though. If any pieces are still missing, I believe your search engine can supply them. – Ole V.V. Dec 21 '19 at 14:14
  • 1
    The answers posted so far are hand calculating the hours and the minutes. I recommend that instead you leave that calculation to library methods to the greatest extend possible. The `Duration` class from java.time and/or ThreeTenABP will be very helpful. – Ole V.V. Dec 21 '19 at 14:16

2 Answers2

1
 String posttime=1576917051506  
 String currenttime=ServerValue.TIMESTAMP

first of all convert times to Long

   long time1 = Long.valueof(posttime)
   long time2 = Long.valueof(currenttime)
   long diffrence  = time2-time1
   String myValue = convertSecondsToHMmSs(diffrence)

Now myValue is your time diffrence. like 1h:2m

  public static String convertSecondsToHMmSs(long millis) {
       long seconds = (millis / 1000) % 60;
long minutes = (millis / (1000 * 60)) % 60;
long hours = millis / (1000 * 60 * 60);

StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) : 
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :     
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) : 
String.valueOf(seconds));
return b.toString();
    }
Deepak Ror
  • 2,084
  • 2
  • 20
  • 26
1

Using Joda time:

DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
long hours = p.getHours();
long minutes = p.getMinutes();
Masum
  • 1,037
  • 15
  • 32
  • 1
    Using Joda-Time may be a good suggestion in this case. That project is in maintenance mode, but it may be offering the best you can have on Android. – Ole V.V. Dec 21 '19 at 14:20