How do I get today’s date and time?

This example show you how to use the new Date and Time API introduced in JDK 8 to get the current date and time. To get today’s date in this new API you can construct an instance of LocalDate, LocalTime or LocalDateTime and call its toString() method.

All of these classes is located under the new java.time package, and defined as a final class, and because theirs constructor declared as a private constructor, this mean you can’t use their constructor to create a new instance. But these classes offer some static factory method to get the value it represents or to create a new instance. For example all of these classes provide a now() method that return the current date, time or date and time information.

Let’s see a complete code snippet in the TodayDateTime example to demonstrate it.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class TodayDateTime {
    public static void main(String[] args) {
        // Obtains the current date from the system clock in the
        // default time-zone.
        LocalDate currentDate = LocalDate.now();
        System.out.println("currentDate = " + currentDate);

        // Obtains the current time from the system clock in the
        // default time-zone.
        LocalTime currentTime = LocalTime.now();
        System.out.println("currentTime = " + currentTime);

        // Obtains the current date-time from the system clock
        // in the default time-zone.
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("currentDateTime = " + currentDateTime);
    }
}

Running this program will give you the following result:

currentDate = 2021-11-14
currentTime = 23:14:47.694204500
currentDateTime = 2021-11-14T23:14:47.694204500
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.