In Java applications, it’s common to want to get the current date and time, whether you are making a scheduler, a logging system, or a time-sensitive feature. In Java, there are many ways by which you can obtain and manipulate dates, from the legacy Date and Calendar classes to the current, thread-safe java.time API that came with Java 8. In this article, you will learn different ways of getting the current date and time in Java, how to compare dates, how to format dates using SimpleDateFormat or printf patterns, how to convert a String into a date, and how to time the elapsed time.
Table of Contents:
Getting the Current Date and Time in Java
There are several approaches to retrieve the current date and time in Java. The recommended way is to use java.time API, which is available since Java 8, but older approaches like Date and Calendar are still widely used in the code.
Here are some different methods to get the current date and time:
- Using Date Class
- Using the get() method of the Calendar class
- Using the calendar and the formatter class to print the current dates in a specific format
- Using java.time.LocalDate
- Using java.time.LocalTime
- Using java.time.LocalDateTime
- Using java.time.Clock
- Using java.sql.Date
Method 1: Using the Date Class
Developers commonly used the java.util.Date class to represent and manipulate dates, before java.time package is introduced in Java 8. However, it is considered a legacy now, because it is still widely found in the older applications and interviews. You can create a new Date object to get the current date and time in the system.
Example:
Output:
The above code in Java creates a Date object representing the current system date and time and prints it to the console using System.out.println().
Method 2: Using the Calendar Class and get() Method
The Calendar class in Java is part of the java.util package, which is more flexible than the Date class. By using the calendar.getInstance(), you can easily get the current date and time, and then can also extract the specific fields, such as year, month, day, hour, minute, and second, using the get() method.
Example:
Output:
This code shows that the Calendar class is used to get the current date and time, which extracts and prints the components such as year, month, day, hour, minute, and second to the console.
The Calendar class can be used with “SimpleDateFormat”, which allows for the display of dates and times in whatever format is needed. The Calendar class gives you the date and time instance, but “SimpleDateFormat” formats that date into a human-readable string for a pattern, e.g., dd/MM/yyyy, HH:mm:ss.
Example:
Output:
The above code gets the current date and time using Calendar, then formats it into a readable string (dd/MM/yyyy HH:mm:ss) with SimpleDateFormat before printing it to the console.
Method 4: Using java.time.LocalDate
The LocalDate class was introduced in Java 8, as a part of the java.time package that represents a date without any time or timezone information (just year, month, and day) is the standard method of capturing dates as needed. LocalDate is a modern replacement for Date and Calendar if you just need to deal with the date.
Example:
Output:
The code shows the modern Java 8+ Date-Time API by using LocalDate.now() to fetch today’s date (year, month, and day) without time or timezone, making it a cleaner alternative to legacy Date and Calendar classes.
Method 5: Using java.time.LocalTime
The LocalTime class is introduced in Java 8 as part of the java.time package, which represents the time of day (hours, minutes, seconds, nanoseconds) without any date or timezone information.
Example:
Output:
The above code uses LocalTime.now() to get the current system time (hours, minutes, seconds, and nanoseconds) and prints it to the console.
Method 6: Using java.time.LocalDateTime
The LocalDateTime class is also introduced in Java 8 as part of the java.time package represents both date and time together, but without any timezone information. It combines the features of LocalDate and LocalTime in a single object.
Example:
Output:
In this code, the current date and time are obtained using LocalDateTime.now(), formatted with DateTimeFormatter to replace the default T with a space, and printed in a readable yyyy-MM-dd HH:mm:ss format.
Method 7: Using java.time.Clock
The Clock class in Java 8 provides access to the current date and time using a specific time zone or clock system. Unlike LocalDateTime.now(), which gets the current time directly, the Clock function gives you more control and is especially useful for testing and time zone-sensitive applications.
Example:
Output:
In the above code Clock.systemDefaultZone() is used to get the current system time, then prints the date and time separately with a space instead of the default T separator.
Method 8: Using java.sql.Date
The java.sql.Date class is a subclass of java.util.Date, which is designed specifically to represent SQL DATE values, which means that it stores only the year, month, and day (no time information). It is mainly used when working with JDBC and relational databases.
Example:
Output:
In the above code, a java.sql.Date object is created from the current system time in milliseconds and prints only the date part (year, month, day) without time details.
Date Comparison in Java
Comparing dates is a common operation that is used for validating deadlines, checking expiration dates, and sorting records. Java offers multiple methods for comparing dates. The three methods to compare dates are:
- Using compareTo() Method
- Using before() and after() Methods
- Using equals() Method
1. Using compareTo() Method
The compareTo() method belongs to the Comparable interface and can be utilized to compare two Date objects.
- Returns 0 → if both the dates are equal.
- Returns < 0 → if the first date is before the second.
- Returns > 0 → if the first date is after the second.
Example:
Output:
This code shows that two Date objects, date1 as the current time and date2 as 10 seconds later, are created, and the compareTo() method is used to compare the two Date objects by their timestamp in milliseconds, and finally print a message to the console which indicates whether date1 is before, after, or equal to date2.
2. Using before() and after() Methods
The before() and after() methods in the Date class are a very straightforward way to see if one date is before or after another date, and they both return a Boolean.
- date1.before(date2) → true if date1 is before date2.
- date1.after(date2) → true if date1 is after date2.
Example:
Output:
This code shows the comparison between two dates by using the before() and after() methods of the Date class. In this code, two dates, date1 as now, and date2 as 10 seconds later, are created, and it is checked whether date1 is before date2 and whether date2 is after date1. Then, finally, it is printed to the console.
3. Using equals() Method
The equals() method in the Date class checks whether two date objects represent the exact same millisecond value. Unlike before() or after(), it only returns true if both dates are identical in time.
Example:
Output:
This code shows the use of the equals() method in the Date class to check equality. In this code, two Date objects with the same timestamp are created and printed as equal since both represent the exact same millisecond in time.
Get 100% Hike!
Master Most in Demand Skills Now!
The SimpleDateFormat class from java.text is one of the most common ways to format and parse dates in Java. It allows you to convert a Date object into a custom string representation and vice versa.
Here are common format codes used with SimpleDateFormat:
Symbol |
Meaning |
Example |
y |
Year |
2025 |
M |
Month (1-12) |
09 or Sep |
d |
Day of month |
09 |
E |
Day of week |
Tue |
H |
Hour (0-23) |
18 |
h |
Hour (1-12) |
06 |
m |
Minute |
10 |
s |
Second |
42 |
a |
AM/PM marker |
PM |
z |
Time zone |
IST |
Example:
Output:
This code shows how the SimpleDateFormat is used to convert the current Date object into a custom string format (dd-MM-yyyy HH:mm:ss) and prints the formatted date and time.
Parsing Strings into Dates
Sometimes, dates come as strings (e.g., “09-09-2025 19:15:30”) and need to be converted into a Date object for manipulation or comparison. In Java, this is done using the parse() method of the SimpleDateFormat class.
Example:
Output:
The code shows how to convert a date string into a Date object using SimpleDateFormat.parse(). The pattern “dd-MM-yyyy HH:mm:ss” matches the input string, and the parsed Date is then printed in the system’s default format.
Sleeping for a While
In Java, you can pause the execution of a program temporarily using the Thread.sleep() method. This is useful for delays, scheduling, or simulating time-consuming tasks.
Example:
Output:
The code demonstrates how to pause a Java program using Thread.sleep(). It prints “Start,” waits for 3 seconds (3000 milliseconds), and then prints “End after 3 seconds.” The method can throw an InterruptedException, and only the current thread is paused while others continue running.
Measuring Elapsed Time
Measuring elapsed time is useful for performance testing, benchmarking, or tracking execution duration. Java provides multiple ways to do this, primarily using System.currentTimeMillis() or System.nanoTime().
Example 1: Using System.currentTimeMillis()
Output:
This code shows how the time taken to execute a loop performing 1,000,000 square root calculations can be measured in Java. It records the start and end time using System.currentTimeMillis() and prints the elapsed time in milliseconds, showing how long the operation took.
Example 2: Using System.nanoTime() for Higher Precision
Output:
This code calculates the precise time taken to execute a loop performing 1,000,000 square root calculations. It uses System.nanoTime() to record start and end times, then prints the elapsed time in nanoseconds, providing higher-resolution timing than currentTimeMillis().
GregorianCalendar Class
The GregorianCalendar class is a subclass of the Calendar class and provides the default calendar system. It is also the most frequently used calendar object in Java applications by developers. It makes it easier for you to get, set, and work with dates and times.
Key features of GregorianCalendar:
- It holds the entire date and time: year, month, day, hour, minute, and second.
- It also automatically handles leap years.
- This class is capable of simple date calculations like adding or subtracting days, months, or years.
- The GregorianCalendar class is appropriate for calendar-centric applications and working with a pre-Java 11 standard library.
Example:
Output:
This code uses the GregorianCalendar class to get the current date and time. It helps to access the year, month, day, hour, minute, and second individually and then at last prints them in a readable format, adjusting the month since it’s zero-based.
Conclusion
Dealing with dates and times is a key aspect of writing robust Java applications. Regardless of whether you are using modern java.time API classes such as LocalDate and LocalTime or the older Date and Calendar classes, and even some associated formatting tools (e.g., SimpleDateFormat and printf date and time patterns), make working with dates simple. Once you understand these components, you can get and use the current date and time reliably and easily in your Java program. Calendar classes such as GregorianCalendar and java.sql.Date are quite useful when working with calendars and databases, respectively.
How to Get the Current Date and Time in Java – FAQs
Q1. What is the difference between Date and LocalDate in Java?
The difference between Date and LocalDate is that Date is mutable and part of the legacy API, and LocalDate is immutable, thread-safe, and more modern.
Q2. How do I format a date in Java?
You can use SimpleDateFormat for legacy code and DateTimeFormatter for Java 8+ to change the date format.
Q3. How can I compare two dates in Java?
You can use compareTo(), isBefore(), isAfter(), and isEqual() for comparing dates in Java.
Q4. How do I measure execution time in Java?
You should use System.currentTimeMillis() for milliseconds or System.nanoTime() for measuring execution time in Java.
Q5. Is SimpleDateFormat thread-safe?
No, SimpleDateFormat is not thread-safe. For multi-threaded applications, you should use DateTimeFormatter instead of this one.