2

I get time from the server like this 2018-11-27T09:51:31.832107+00:00, then I parse the time so OffsetDateTime.parse. I want to differentiate between the two times OffsetDateTime.now - OffsetDateTime.parse.

After subtraction, I have to show the elapsed time in this form: 14 min 12 seconds. How can I do it right to get a span-of-time?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
TikTak
  • 713
  • 1
  • 11
  • 23
  • 2
    Did you search/try anything? – achAmháin Dec 21 '18 at 09:33
  • 1
    @OleV.V. After subtraction, I have to show the time in this form `14 min 12 seconds` – TikTak Dec 21 '18 at 10:06
  • Thanks for the added precision, it makes it a lot easier to answer the question. When adding information, please do so in the question itself so we have everything in one place (this time I did it for you). – Ole V.V. Dec 21 '18 at 10:15

3 Answers3

3

It’s easy when you know how:

// Parse input.
String timeFromServer = "2018-11-27T09:51:31.832107+00:00";
OffsetDateTime odt = OffsetDateTime.parse(timeFromServer);

// Capture the current moment. 
OffsetDateTime now =  OffsetDateTime.now(ZoneOffset.UTC)

// Get the difference
Duration difference = Duration.between(odt,now);

// Extract details: Convert to minutes and seconds
long minutes = difference.toMinutes();
difference = difference.minusMinutes(minutes);
long seconds = difference.getSeconds();

// Format into string in desired form
String formattedDiff = String.format("%d min %d seconds", minutes, seconds);
System.out.println(formattedDiff);

When run now we get a large number of minutes since your example string is from last month.

34613 min 38 seconds

The only tricky part is splitting out the minutes and the seconds from the Duration object. I take out the minutes first, then subtract them so only the seconds (and smaller) are left. From Java 9 Duration has improved support for getting the individual units of time (see to…Part methods), but I suppose you can’t use that on Android yet.

When it’s only for calculating the difference, it doesn’t matter which time zone or offset you pass to OffsetDateTime.now.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

You have, in android a mehtod that's called "compare", it may help you, see documentation here :

https://developer.android.com/reference/java/time/OffsetDateTime#compareTo(java.time.OffsetDateTime)

0

Convert two times in milliseconds and after that subtract second milliseconds from first milliseconds and then format the result into verbal date.