java get current date

java

To get the current date and time in Java, you can use the java.time.LocalDateTime class from the java.time package. This class represents a date-time without a time-zone in the ISO-8601 calendar system, such as 2021-12-03T10:15:30.

Here is an example of how you can use the LocalDateTime class to get the current date and time:

import java.time.LocalDateTime;

public class Main {
  public static void main(String[] args) {
    LocalDateTime currentTime = LocalDateTime.now();
    System.out.println("Current date and time: " + currentTime);
  }
}

This will output the current date and time in the following format: “Current date and time: 2021-12-03T10:15:30”.

You can also use the java.util.Date class from the java.util package to get the current date and time. This class represents a specific instant in time, with millisecond precision.

Here is an example of how you can use the Date class to get the current date and time:

import java.util.Date;

public class Main {
  public static void main(String[] args) {
    Date currentTime = new Date();
    System.out.println("Current date and time: " + currentTime);
  }
}

This will output the current date and time in the following format: “Current date and time: Fri Dec 03 10:15:30 PST 2021”.

Note: The java.time package was introduced in Java 8, and it is recommended to use this package for working with dates and times in Java. The java.util.Date class is deprecated in Java 8, and it is recommended to use the java.time.LocalDateTime class instead.