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 are located under the new java.time
package, and defined as final classes, and because their constructor is declared as a private constructor, it means you can’t use their constructor to create a new instance. But these classes offer some static factory methods 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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024