java.time
ZoneId zone = ZoneId.of("America/Chicago");
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a (OOOO)", Locale.US);
LocalDate startDate = LocalDate.of(2019, Month.SEPTEMBER, 18);
LocalTime startTime = LocalTime.of(14, 0);
LocalTime endTime = LocalTime.of(4, 0);
ZonedDateTime start = ZonedDateTime.of(startDate, startTime, zone);
ZonedDateTime end = ZonedDateTime.of(startDate, endTime, zone);
if (end.isBefore(start)) {
end = ZonedDateTime.of(startDate.plusDays(1), endTime, zone);
}
System.out.println("Date: " + startDate);
System.out.println("Start Time: " + start.format(timeFormatter));
System.out.println("End Time: " + end.format(timeFormatter));
System.out.println("Ends on " + end.toLocalDate());
Output from this snippet is:
Date: 2019-09-18
Start Time: 2:00 PM (GMT-05:00)
End Time: 4:00 AM (GMT-05:00)
Ends on 2019-09-19
I have shown you how to use a DateTimeFormatter
for formatting the times. You will probably want to use formatters for the dates too.
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