Java – Get Current Date and Current Time
To get both current date and current time in Java
- Import LocalDateTime class from java.time package.
- Create LocalDateTime object by calling static method now() of LocalDateTime class. LocalDateTime.now() returns the current date and current time from the system clock in the default time zone.
- Call toString() method on this LocalDateTime object. toString() method returns the current date and time as a String.
Example
In the following program, we shall use LocalDateTime class of java.time package and get the the current date and current time.
Java Program
</>
Copy
import java.time.LocalDateTime;
public class Example {
public static void main(String[] args) {
LocalDateTime dateTimeObj = LocalDateTime.now();
String currentDateTime = dateTimeObj.toString();
System.out.println(currentDateTime);
}
}
Output
2021-02-18T09:52:16.660971
LocalDateTime.toString() method returns date and time in the format: yyyy-MM-ddTHH:mm:ss.ns
. We can format this LocalDateTime object into any required pattern using DateTimeFormatter. Following are some of the tutorials, that provide examples to format Date and Time.
Conclusion
In this Java Tutorial, we learned how to get current date and time using LocalDateTime class of java.time package, with example program.