Sub topic 3
Measuring Date-Based Amounts with Period
Period: Years, Months, and Days
A Period is an amount of time counted in calendar units: years, months, and days. You can use one to answer a question like "how old is this account?"
ChronoUnit is a set of units, such as DAYS or MONTHS. Each unit can count how many of itself fit between two dates, and the answer comes back as a single number.
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Amounts {
public static void main(String[] args) {
Period p = Period.between(LocalDate.of(2020, 1, 15), LocalDate.of(2024, 3, 10));
System.out.println(p); // P4Y1M24D
long days = ChronoUnit.DAYS.between(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 12, 31));
System.out.println(days); // 365
}
}P4Y1M24D means 4 years, 1 month, and 24 days. A Period keeps each part separate, while ChronoUnit gives you one total.
Formatting and Parsing
A DateTimeFormatter turns dates into text and text into dates. It uses a pattern, which is a template made of letters: dd is the day, MM is the month number, MMM is the short month name, and yyyy is the year.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Formatting {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("05/11/2024", DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(date); // 2024-11-05
System.out.println(date.format(DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.US))); // Nov 5, 2024
}
}Shortcuts with TemporalAdjusters
A TemporalAdjuster is a ready-made rule for moving a date, such as "last day of the month." You pass one to with(), so you don't have to do the arithmetic yourself.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class Adjusters {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 11, 5);
System.out.println(date.with(TemporalAdjusters.lastDayOfMonth())); // 2024-11-30
System.out.println(date.with(TemporalAdjusters.next(DayOfWeek.FRIDAY))); // 2024-11-08
}
}Daylight Saving Time
Daylight saving time (DST) means moving clocks forward one hour in spring and back one hour in autumn. On the spring day, some local times never happen. Java moves a time that falls in that gap forward. The same change makes that calendar day only 23 hours long.
import java.time.*;
public class DaylightSaving {
public static void main(String[] args) {
ZoneId ny = ZoneId.of("America/New_York");
System.out.println(ZonedDateTime.of(LocalDateTime.of(2024, 3, 10, 2, 30), ny));
// 2024-03-10T03:30-04:00[America/New_York]
ZonedDateTime start = LocalDate.of(2024, 3, 10).atStartOfDay(ny);
System.out.println(Duration.between(start, start.plusDays(1))); // PT23H
}
}Testable Time with Clock, and Legacy Types
A Clock is the source that now() reads the current time from. A fixed clock always returns the same moment, which makes tests predictable.
To work with older code that still uses java.util.Date, convert through Instant.
import java.time.*;
import java.util.Date;
public class ClockAndLegacy {
public static void main(String[] args) {
Clock fixed = Clock.fixed(Instant.parse("2024-01-01T00:00:00Z"), ZoneOffset.UTC);
System.out.println(LocalDate.now(fixed)); // 2024-01-01
Date legacy = new Date();
Date back = Date.from(legacy.toInstant());
System.out.println(legacy.equals(back)); // true
}
}Exercise
You need the total number of months between two dates as one number. Should you use Period.between or ChronoUnit.MONTHS.between?
Show answer
Use ChronoUnit.MONTHS.between. It returns a single total count. Period.between splits the answer into separate years, months, and days.