The LocalTime Class
The declaration statements below show examples of creating instances of the LocalTime class to represent time on a 24-hour clock in terms of hours, minutes, seconds, and nanoseconds.
LocalTime time1 = LocalTime.of(8, 15, 35, 900); // 08:15:35.000000900
LocalTime time2 = LocalTime.of(16, 45); // 16:45
// LocalTime time3 = LocalTime.of(25, 13, 30); // DateTimeException
The ranges of values for time fields hour (0–23), minute (0–59), second (0–59), and nanosecond (0–999,999,999) are defined by the ISO standard. The toString() method of the class will format the time fields according to the ISO standard as follows:
HH:mm:ss.SSSSSSSSS
Omitting the seconds (ss) and fractions of seconds (SSSSSSSSS) in the call to the of() method implies that their value is zero. (More on formatting in §18.6, p. 1134.) In the second declaration statement above, the seconds and the nanoseconds are not specified in the method call, resulting in their values being set to zero. In the third statement, the value of the hour field (25) is out of range, and if the statement is uncommented, it will result in a DateTimeException.
The LocalDate Class
Creating instances of the LocalDate class is analogous to creating instances of the LocalTime class. The of() method of the LocalDate class is passed values for date fields: the year, month of the year, and day of the month.
LocalDate date1 = LocalDate.of(1969, 7, 20); // 1969-07-20
LocalDate date2 = LocalDate.of(-3113, Month.AUGUST, 11);// -3113-08-11
// LocalDate date3 = LocalDate.of(2021, 13, 11); // DateTimeException
// LocalDate date4 = LocalDate.of(2021, 2, 29); // DateTimeException
The ranges of the values for date fields year, month, and day are (–999,999,999 to +999,999,999), (1–12), and (1–31), respectively. The month can also be specified using the enum constants of the java.time.Month class, as in the second declaration statement above. A DateTimeException is thrown if the value of any parameter is out of range, or if the day is invalid for the specified month of the year. In the third declaration, the value of the month field 13 is out of range. In the last declaration, the month of February cannot have 29 days, since the year 2021 is not a leap year.
The toString() method of the LocalDate class will format the date fields according to the ISO standard (§18.6, p. 1134):
uuuu-MM-dd
The year is represented as a proleptic year in the ISO standard, which can be negative. A year in CE (Current Era, or AD) has the same value as a proleptic year; for example, 2021 CE is the same as the proleptic year 2021. However, for a year in BCE (Before Current Era, or BC), the proleptic year 0 corresponds to 1 BCE, the proleptic year –1 corresponds to 2 BCE, and so on. In the second declaration in the preceding set of examples, the date -3113-08-11 corresponds to 11 August 3114 BCE.