Week 70 — How can one get the current date and time in a Java application?
Question of the Week #70
How can one get the current date and time in a Java application?
9 Replies
Java allows obtaining the current time in milliseconds since the UNIX epoch (1.1.1970) using the method
System.currentTimeMillis()
.
However, the java.time
API provides many other ways of working with times and dates which also includes options for getting the current date/time.
For example, it is possible to obtain an Instant
representing the current timestamp (without any timezone information) using the method Instant.now()
.
Similarly, one can get the current date and time (using the system timezone) using LocalDateTime.now()
(or LocalDate.now()
for the date and LocalTime.now()
for the time).
If additional timezone information is needed, one can use ZonedDateTime.now()
which returns the current date and time including information about the system timezone.
📖 Sample answer from dan1st
Using the Date class to get current date and time in Java:
import java.util.Date;
import java.util.Date;
public class CurrentDateTimeExample {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date); // Prints current date and time in a specific format
}
}
/*This code only prints the date in Day_Month_Day_Number and time in HH:MM:SS formats
*/
Submission from tgamerboy_02
Submission from elspon
LocalDateTime.now()
Use this to get current date and time
Submission from ishaik921
Calender package helps us find the current date and time.
You must handle the changes if you want time in local time zone on your side.
Date package is deprecated it was used previously to find current date and time.
Submission from sk001
We use LocalDateTime.now() method to obtain the current date and time and boom! We find ourselves obtaining the current date and time in a Java application.
Submission from jaymoney95
LocalDateTime.now();
Submission from roadgeek878
Numerous ways:
⭐ Submission from dangerously_casual