I'm using this library I just discovered which is supposedly less heavier than Joda time for android and I said what the heck, let's use it. But now I'm struggling to find any good examples on the web about how to use it, besides these two methods I have:
// ZonedDateTime contains timezone information at the end
// For example, 2011-12-03T10:15:30+01:00[Europe/Paris]
public static ZonedDateTime getDate(String dateString) {
return ZonedDateTime.parse(dateString).withZoneSameInstant(ZoneId.of("UTC"));
}
public static String formatDate(String format, String dateString) {
return DateTimeFormatter.ofPattern(format).format(getDate(dateString));
}
So how can I get the difference between two dates with this library?
There are several options depending on what you require from the difference you obtain.
It’s easiest to find the difference measured in some time unit. Use
ChronoUnit.between
. For example:This prints:
I am using your
getDate
method, so the format required is that ofZonedDateTime
(modified from ISO 8601), for example2011-12-03T10:15:30+01:00[Europe/Paris]
. Seconds and fraction of second are optional, as is time zone ID in square brackets.BTW you don’t need to convert to UTC before finding the difference. You will get the same result even if you leave out that conversion.
You may also get the difference in years, months and days. The
Period
class can give you this, but it cannot handle time of day, so convert toLocalDate
first:The output means a period of 5 years 11 months 21 days. The syntax may feel a little strange at first, but is straightforward. It is defined by the ISO 8601 standard. In this case the time zone matters since it is never the same date in all time zones.
To get the difference in hours, minutes and seconds use the
Duration
class (I am introducing a new time since usingDuration
for nearly 6 years would be too atypical (though possible)).A period of 13 hours 1 minute 15 seconds. The
T
that you already know from2011-12-03T10:15:30+01:00[Europe/Paris]
here too separates the date part from the time part so you know that in this case1M
means 1 minute, not 1 month.