Home >Java >javaTutorial >How to Get the Current Date and Time in Java?
How to Retrieve the Current Date and Time in Java
Retrieving the current date and time in Java is a common task, but there are several methods to accomplish it, each with its own advantages and disadvantages.
Numerical Value (Milliseconds)
The simplest approach is to obtain the current time as a single numeric value. This is accomplished using System.currentTimeMillis(), which returns the number of milliseconds since the UNIX epoch as a Java long. This value represents a delta from a specific UTC time-point and is independent of the local time zone.
Components as Integers (Date and Calendar)
If you require access to individual date and time components (e.g., year, month), you can utilize one of the following methods:
Joda-Time
Before Java 8, the Joda-Time library was widely recommended for its superior APIs for time point and duration calculations. It offers classes like org.joda.time.DateTime for obtaining the current date and time.
Java 8 (java.time)
Java 8 introduced the java.time package, which provides modern and efficient classes for date and time handling. To retrieve the current date and time, you can use java.time.LocalDateTime.now() and java.time.ZonedDateTime.now().
Note: The timezone should be considered when working with date and time. The platform's default time zone is typically used, but explicitly specifying a time zone can enhance predictability and prevent issues when operating across different time zones.
The above is the detailed content of How to Get the Current Date and Time in Java?. For more information, please follow other related articles on the PHP Chinese website!