Google News
logo
Java Program to Get Current Date/TIme
In the following example of Java program to get the current date/time using the java.time package :
Program :
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentDateTime {
    public static void main(String[] args) {
        // Get the current date/time
        LocalDateTime now = LocalDateTime.now();
        
        // Format the date/time using the desired pattern
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        
        // Print the formatted date/time
        System.out.println("Current date/time: " + formattedDateTime);
    }
}
Output :
Current date/time: 2020-04-21 12:07:52
This program creates a LocalDateTime object representing the current date/time using the now() method of the LocalDateTime class. It then uses the ofPattern() method of the DateTimeFormatter class to create a formatter object with the desired date/time pattern. Finally, it formats the date/time using the formatter object and prints it to the console.