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
2
3
4
5
6
7
8
9
10
11
12
13
LocalDate today = LocalDate.now(); // No public constructor BUT factory methods
System.out.println(today);
LocalDate anoherDate = today.plusDays(2); // Does not change the current instance;
System.out.println("----------------------------");
System.out.println(today); // Time API is IMMUTABLE
System.out.println(anoherDate);


today = today.minusDays(10);
System.out.println(today);

LocalDate aDate = LocalDate.of(2018, 6, 15);
System.out.println(aDate);

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
2
3
4
5
6
7
8
9
10
LocalDate today = LocalDate.now();
Period p = Period.of(1, 5, 10);
System.out.println(p); // Specific Format
Period normalized = p.normalized();
System.out.println(normalized);

Period p2 = Period.of(1, 25, 10);
System.out.println(p2); // Specific Format
Period normalized2 = p2.normalized();
System.out.println(normalized2);

Temporal Units

Temporal Units

1
2
3
LocalTime nineThirtheen = LocalTime.of(9, 13);
System.out.println(nineThirtheen);
//LocalTime muchLater = nineThirtheen.plus(period); // java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Months

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
2
3
LocalDate today = LocalDate.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("d MM yy");
System.out.println(fmt.format(today));
  • 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