Sub topic 2
DayOfWeek, Month, YearMonth, and MonthDay
The java.time package has small helper types for parts of a date, and further types for real moments in time. This chapter covers both groups and ends with Duration.
Parts of a Date
DayOfWeekis an enum (a fixed list of named values) holding MONDAY through SUNDAY.Monthis an enum holding JANUARY through DECEMBER.YearMonthis a year plus a month with no day, such as a card expiry date.MonthDayis a month plus a day with no year, such as a birthday.
import java.time.DayOfWeek;
import java.time.Month;
import java.time.MonthDay;
import java.time.YearMonth;
public class Parts {
public static void main(String[] args) {
System.out.println(DayOfWeek.FRIDAY.plus(3)); // MONDAY
System.out.println(Month.MARCH.plus(11)); // FEBRUARY
System.out.println(YearMonth.of(2024, 2).lengthOfMonth()); // 29
System.out.println(MonthDay.of(12, 25)); // --12-25
}
}Instant, Zones, and Offsets
An Instant is one exact point on the timeline. It counts time from the epoch, which is 1970-01-01T00:00:00Z. The "Z" means UTC, the world's reference time.
A ZoneId names a time zone region, such as "America/New_York". A ZoneOffset is a fixed gap from UTC, such as -04:00. One zone can have different offsets during the year because of daylight saving time.
A ZonedDateTime is a date, a time, and a zone together. You can show the same instant in another zone with withZoneSameInstant:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Zones {
public static void main(String[] args) {
LocalDateTime meeting = LocalDateTime.of(2024, 7, 1, 9, 0);
ZonedDateTime newYork = meeting.atZone(ZoneId.of("America/New_York"));
ZonedDateTime tokyo = newYork.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
System.out.println(newYork); // 2024-07-01T09:00-04:00[America/New_York]
System.out.println(tokyo); // 2024-07-01T22:00+09:00[Asia/Tokyo]
System.out.println(newYork.toInstant()); // 2024-07-01T13:00:00Z
}
}An OffsetDateTime holds a date, a time, and a fixed offset, with no zone rules. It is a good fit for databases and JSON, because a fixed offset means the same thing everywhere.
Duration
A Duration is an amount of time in hours, minutes, seconds, and nanoseconds.
import java.time.Duration;
public class Durations {
public static void main(String[] args) {
Duration d = Duration.ofMinutes(135);
System.out.println(d); // PT2H15M
System.out.println(d.toHours()); // 2
}
}PT2H15M means "a period of time of 2 hours and 15 minutes." toHours() drops the leftover minutes.
Exercise
A store wants to save a card's expiry date, which has only a month and a year. Which type should it use?
Show answer
YearMonth, because it holds a year and a month with no day.
Exercise
What does Duration.ofMinutes(90).toHours() return?
Show answer
1, because toHours() returns whole hours and drops the remaining 30 minutes.