Time for the modern answer.
java.time and ThreeTenABP
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
String validUntil = "1/1/1990";
LocalDate validDate = LocalDate.parse(validUntil, dateFormatter);
LocalDate currentDate = LocalDate.now(ZoneId.of("Pacific/Efate"));
if (currentDate.isAfter(validDate)) {
System.out.println("Catalog is outdated");
}
When I ran this code just now, the output was:
Catalog is outdated
Since it is never the same date in all times zones, give explicit time zone to LocalDate.now
. If you want the catalog to expire at the same time in all time zones, you may give ZoneOffset.UTC
as long as you inform you users that you are using UTC.
I am using java.time, the modern Java date and time API. The date-time classes that you used, Calendar
, SimpleDateFormat
and Date
, are all poorly designed and fortunately long outdated. Also despite the name a Date
doesn’t represent a date, but a point in time. One consequence of this is: even though today is February 15, 2019, a newly created Date
object is already after (so not equal to) a Date
object from parsing 15/02/2019
. This confuses some. Contrary to this the modern LocalDate
is a date without time of day (and without time zone), so two LocalDate
s representing today’s date will always be equal.
Question: Can I use java.time on Android?
Yes, java.time works nicely on 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 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