Java Date-API explained

The java.time package in Java provides a comprehensive set of classes for working with dates, times, and durations. These classes are part of the Java Date-Time API, which is a new API introduced in Java 8 that replaces the legacy java.util.Date and java.util.Calendar classes.

Here are some examples of using the java.time API to work with dates and times in Java:

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;

public class Main {
    public static void main(String[] args) {
        // Get the current date and time
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println(currentDateTime);

        // Get the current date
        LocalDate currentDate = LocalDate.now();
        System.out.println(currentDate);

        // Get the current time
        LocalTime currentTime = LocalTime.now();
        System.out.println(currentTime);

        // Create a specific date and time
        LocalDateTime specificDateTime = LocalDateTime.of(2020, Month.JANUARY, 1, 12, 0, 0);
        System.out.println(specificDateTime);

        // Extract the date and time components
        int year = specificDateTime.getYear();
        Month month = specificDateTime.getMonth();
        int day = specificDateTime.getDayOfMonth();
        int hour = specificDateTime.getHour();
        int minute = specificDateTime.getMinute();
        int second = specificDateTime.getSecond();
        System.out.println(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);
    }
}

In this example, the LocalDateTime class is used to represent a date and time, the LocalDate class is used to represent a date, and the LocalTime class is used to represent a time. The now method is used to get the current date and time, and the of method is used to create a specific date and time. The various get methods are used to extract the different components of a date and time.

The java.time API also includes classes for working with durations, such as the Duration and Period classes. These classes can be used to perform arithmetic on dates and times, such as adding or subtracting a specific amount of time.