Correct way to Get the Current Date in Java 8 or above

The correct way to get the current date in Java as a best practice is to use the java.time package that was introduced in Java 8 and later.

Make use of the LocalDate class to obtain the current date.


Example:

import java.time.LocalDate;

public class Example {

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

        LocalDate currentDate = LocalDate.now();
        System.out.println("Current Date: " + currentDate);

    }

}

Output:

Current Date: 2023-10-18

The LocalDate.now() method returns the current date in the default system time zone.

This is recommended because it's part of the modern Java Date and Time API, which provides better functionality and improved date/time handling compared to the older java.util.Date and java.text.SimpleDateFormat classes.

Note: Make sure you are using Java 8 or a later version to use the java.time package.


Documentaion: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDate.html

Comments & Discussion

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