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.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap