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
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023