Java Time API
API
- java.time Package
- java.time.LocalDate (*),
- java.time.LocalTime (*)
- java.time.LocalDateTime (*),
- java.time.Period(*),
- java.time.format.DateTimeFormatter (*),
java.time.Duration,
(*) subject for exams
Java Time API
Create
No Constructors (only private), but factory method : LocalDate.of…
DateTime API is IMMUTABLE
Methods :
aLocalDate.plusDays(2);
aLocalDate.minusDays(10);
1 | LocalDate today = LocalDate.now(); // No public constructor BUT factory methods |
Ex
Retrieve current week’s Monday’s date
1 | LocalDate previousMonday = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ); |
Duration vs Period
- Period : Only interest in Year, Month, Day (more restriction)
Human Calendar Period (1 month, 3 days or 2 years, 4 days..) - Duration : interest in Year, Month, Day, hour, minutes, seconds : nanoseconds
Physical Duration in nanoseconds
Period has a specific print format : P1Y5M10D for a Period of 1 year, 5 month, 10 days
Normalized can change month to year but not days to month or year
aLocalDate.plus(aPeriod);
1 | LocalDate today = LocalDate.now(); |
Temporal Units
1 | LocalTime nineThirtheen = LocalTime.of(9, 13); |
BE CAREFULL : Of adding period (y/m/d) to Time (LocalTime) : Error !!!!
Time Formatter
java.time.format
- DateTimeFormatter
ex : LocalDate parsedDate = LocalDate.parse(text, formatter);
1 | LocalDate today = LocalDate.now(); |
- Cannot interact whith “Temporal Units” that are not supported by the “thing” you give it (LocalDate etc…)
- Number of chars in a format specify String changes the results representation