In Java, the Date and Time API (java. time package) provides a rich set of classes for representing and manipulating date and time values.
The most important classes in the Date and Time API are
● LocalDate: represents a date (year, month, and day) without a time or time zone.
● LocalTime: represents a time of day (hour, minute, and second) without a date or time zone.
● LocalDateTime: represents a date and time without a time zone.
● ZonedDateTime: represents a date and time with a time zone.
Ex :
LocalDate date = LocalDate.of(2022, 3, 25);
The above code creates a LocalDate object representing the date "2022-03-25" LocalTime time = LocalTime.of(12, 15, 30);
The above code creates a LocalTime object representing the time "12:15:30"
You can also create LocalDateTime and ZonedDateTime objects by combining date and time. For example, the following code creates a LocalDateTime object representing the date and time "2022-03-25T12:15:30":
LocalDateTime dateTime = LocalDateTime.of(date, time);
Java also provides a class called Instant, which represents a point in time in the format of a timestamp. Instant can be used to represent both the date and time values.
Example:
Instant instant = Instant.now();
Java also provides several classes for working with durations, such as Period and Duration.
A period is used to represent a duration in terms of years, months, and days. Duration is used to represent a duration in terms of seconds and nanoseconds.
Example:
LocalDate start = LocalDate.of(2022, 3, 25);
LocalDate end = LocalDate.of(2022, 5, 25);
Period period = Period.between(start, end);
long seconds = Duration.between(time1, time2).getSeconds();
Java also provides a way to format date and time values using the DateTimeFormatter class. This class provides a variety of predefined formatters, such as ISO_LOCAL_DATE, ISO_LOCAL_TIME, and ISO_LOCAL_DATE_TIME, as well as the ability to create custom formatters.