java.time and ThreeTenABP
Edit: revised the code after new information, and smoke tested.
the due date can be today or in the future.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MMM-uu", Locale.ROOT);
ZoneId zone = ZoneId.systemDefault();
ZonedDateTime now = ZonedDateTime.now(zone);
String dueDateString = "01-Dec-19";
LocalDate dueDate = LocalDate.parse(dueDateString, dateFormatter);
LocalDate today = now.toLocalDate();
if (dueDate.equals(today)) {
System.out.println("Due date is today");
} else {
// Count days from tomorrow and then hours until start of day tomorrow
LocalDate tomorrow = today.plusDays(1);
long days = ChronoUnit.DAYS.between(tomorrow, dueDate);
ZonedDateTime startOfDayTomorrow = tomorrow.atStartOfDay(zone);
long hours = ChronoUnit.HOURS.between(now, startOfDayTomorrow);
System.out.println("Due date will be in " + days + " days " + hours + " hours");
}
When I ran the code just now in my time zone (Europe/Copenhagen), the output was:
Due date will be in 1 days 2 hours
I am unsure whether this is the exact output that you wanted, but I hope that you can adjust the code to give you what you want.
For Android below API level 26 add the ThreeTenBackport library to your project and make sure to import the date and time classes from org.threeten.bp
with subpackages.
Please give your formatter the correct locale depending on the language of your date string.
The classes Date
, DateFormat
and SimpleDateFormat
are all poorly designed and long outdated, and java,time, the modern Java date and time API, is so much nicer to work with. Also you shouldn't hand calculate days and hours from milliseconds. It's more complicated than what you do in your code, errorprone and harf to read. Rely on well-proven library methods for such a task.
Original code:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MMM-uu", Locale.ROOT);
ZoneId zone = ZoneId.systemDefault();
ZonedDateTime now = ZonedDateTime.now(zone);
String dueDateString = "20-Nov-19";
LocalDate dueDate = LocalDate.parse(dueDateString, dateFormatter);
long days = ChronoUnit.DAYS.between(dueDate, now.toLocalDate());
ZonedDateTime startOfToday = now.toLocalDate().atStartOfDay(zone);
long hours = ChronoUnit.HOURS.between(startOfToday, now);
System.out.println("Due date was " + days + " days " + hours + " hours ago");
Question: Doesn’t java.time require Android API level 26?
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