It’s a general use case for all the applications to know the today’s date in Java. For example, we might need to insert the current or today’s date & time by default when we create a transaction. In this article, we will see different ways to obtain today’s date in Java.

Java Utils Date

To get today’s date, create an instance of java.util.Date class and use the current system time.

Let us first import the required class and see how to get today’s date.

import java.util.*;

public class TodayDateExample {
    public static void main(String[] args) {
        // Create a Date instance representing the current date and time
        Date currentDate = new Date();

        // Print the current date
        System.out.println("Today's Date: " + currentDate);
    }
}

The above code displays the current date and time.

Get today’s date using Java 8 or later

The LocalDate class which is present in the java.time package provides apis for working with dates. Using LocalDate we can represent a date without time or time zone information.

Following is an example of how to get today’s date using java.time.LocalDate class.

import java.time.*;

public class TodayLocalDateExample {
    public static void main(String[] args) {
        // Get the current date without time or time zone
        LocalDate currentDate = LocalDate.now();

        // Print the current date
        System.out.println("Today's Date: " + currentDate);
    }
}

The above code displays the today’s date without time or timezone information.

References:

https://docs.oracle.com/javase/8/docs/api/java/util/Date.html

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

Categorized in:

Tagged in: