How to Get the Current Date and Time in Java 8 and Above

To get the current date and time in Java 8 and above we can make use of LocalDateTime.now().

Example:

package org.code2care.examples;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Example {

    public static void main(String... args) {

        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        
        System.out.println("Current Date and Time: " + formattedDateTime);
    }
}

Output:
Get Current Date and Time - Java 8 and Above

Current Date and Time: 10-18-2023 12:56:19

Note: The code above retrieves the current date and time in the system's default time zone. If you need to work with a specific time zone, you can use ZoneId with the atZone() method to adjust the time zone.

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!