java.time and ThreeTenABP
This will work on your Android API level:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("d MMM uuuu hh:mm ")
.parseCaseInsensitive()
.appendPattern("a")
.toFormatter(Locale.US);
ZoneId zone = ZoneId.of("America/Chicago");
ZonedDateTime currentDateTime = ZonedDateTime.now(zone);
String dateTimeString = "2 Nov 2019 07:30 pm";
ZonedDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter)
.atZone(zone);
long diffInHours = ChronoUnit.HOURS.between(currentDateTime, dateTime);
System.out.println("Difference in hours: " + diffInHours);
When I ran this snippet just now, the output was:
Difference in hours: 541
I am using java.time, the modern Java date and time API. It’s much nicer to work with than the old and poorly designed Date
and SimpleDateFormat
. On one hand parsing lowercase am
and pm
requires a little more code lines (since they are normally in uppercase in US locale), on the other hand java.time validates more strictly, which is always good. Advantages we get for free include: We need no time zone conversions, we can do everything in Central Time. The calculation of the difference in hours is built in, just requires one method call.
Specify locale for your formatter, or it will break when some day your code runs on a JVM with a non-English default locale. Specify US Central Time as America/Chicago. Always use this region/city format for time zones. CST is deprecated and also lying since it gives you CDT at this time of year.
Question: Doesn’t java.time require Android API level 26 or higher?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links