Java Date and Time
Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example:
Class | Description |
---|---|
LocalDate | Represents a date (year, month, day (yyyy-MM-dd)) |
LocalTime | Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns)) |
LocalDateTime | Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns) |
DateTimeFormatter | Formatter for displaying and parsing date-time objects |
If you don’t know what a package is, read our Java Packages Tutorial.
Display Current Date
To display the current date, import the java.time.LocalDate class, and use its now() method:
Example
The output will be:
Display Current Time
To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method:
Example
The output will be:
Display Current Date and Time
To display the current date and time, import the java.time.LocalDateTime class, and use its now() method:
Example
The output will be:
Formatting Date and Time
The «T» in the example above is used to separate the date from the time. You can use the DateTimeFormatter class with the ofPattern() method in the same package to format or parse date-time objects. The following example will remove both the "T" and nanoseconds from the date-time:
Example
The output will be:
The ofPattern() method accepts all sorts of values, if you want to display the date and time in a different format. For example:
How to get current date and time in Java
In this article, we will look at different ways to get the date and time in Java using both legacy classes ( Date & Calendar ) as well as Java 8 new date and time API.
Java 8 introduced a completely new date and time API (classes in the java.time.* package) to address the shortcomings of the existing API ( java.util.Date & java.util.Calendar ). The new API is not only thread-safe but also much more user-friendly, with tons of utility methods for performing different date and time tasks.
As the name suggests, the LocalDate class stores the date in the ISO-8601 format (yyyy-MM-dd) without any time or timezone information. This means that you can only get the current date in the system's default timezone without time.
Here is an example that shows how you can use LocalDate to get the current date:
The above code outputs the following:
The LocalTime class does the opposite of LocalDate . It stores the local time in ISO 8601 format without date or timezone information. This means that you can get the current time of the day without the actual date, as shown below:
You should see the following output if you run the above code snippet:
The LocalDateTime class, the most popular date and time class in Java, holds both local date and time without any timezone information. Here is an example that demonstrates how you can use LocalDateTime to get the current date and time in Java 8 and higher:
Here is what the output of the above code looks like:
Finally, ZonedDateTime is used to store both date and time along with the timezone information. Here is an example that shows how you can get the current zoned date and time using the system's default timezone:
If you run the above code snippet, you should see something like the below printed on the console:
To get the current date and time for a different timezone, you can use the ZoneId identifier as shown below:
Here is the output:
The Instant class represents a specific moment on the timeline. You can use this class to get the current UTC date and time as EPOCH seconds or milliseconds, as shown below:
The above code snippet generates the following output:
Read Introduction to Java 8 Date and Time API tutorial for more new date and time API examples.
Another way of getting the current date and time in Java is using the legacy Date and Calendar classes. All you need to do is create an instance of Date , use SimpleDateFormat to create the desired format, and then pass the date object to the SimpleDateFormat.format() method to get the current date and time as a string.
To get the current date and time, you only need to instantiate the java.util.Date object. Optionally, if you want to display the current date and time in a different format, you can use the SimpleDateFormat class to format the Date object as shown below:
The above code will print the console on the console:
The Calendar class is used for converting between a specific instant in time and a set of Calendar fields. To use Calendar to get the current date and time, you need to do the following:
- Create an instance of Calendar by calling the getInstance() static method.
- Use Calendar.getTime() method to get the current date and time as a Date object.
- Optionally, format the date using SimpleDateFormat to display it in a different format.
Here is an example:
As you can see above, using the Calendar class is as simple as using Date . You create a Calendar instance and then get the current date and time as a Date object. The rest of the code is similar to what we did in the previous example.
By default, the Date and Calendar classes return the current date and time in the default system timezone. To get the current date and time in a different timezone, you need to explicitly set the desired timezone.
Here is an example that shows how you can set the timezone while formatting the Date object using SimpleDateFormat :
The above code will output the following:
If you are using Calendar , you can use the Calendar.setTimeZone() method to change the default timezone to the one you want to, as shown below:
Here is what the output looks like now:
If you only want to get the current date and time as the number of milliseconds passed since the Unix Epoch, use System.currentTimeMillis() . This method returns the current time in milliseconds:
The above code snippet will print the following on the console:
To convert the above milliseconds into human-readable format, you can do the following:
Here is what the output looks like now:
There are many scenarios where you need the current date and time in Java. In this article, we have discussed almost all possible ways to get the current date and time in Java, including Java 8 new date and time API, legacy Date and Calendar classes, and more.
The new date and time API provides an extensive set of classes that has simplified working with date and time in Java 8 and higher. These classes are thread-safe, easier to understand, and backward-compatible.
If you are working on a legacy application that uses the old Date and Calendar API, you can easily convert the legacy code to the new date and time API.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
Get Current Date and Time in Java
Learn to get the current date and/or time in Java. Note that the appropriate way to handle date-time information is different before and after JDK 8.
- For JDK 8 or later, the recommended way is to use LocalDate and LocalTime classes.
- For JDK 7 or earlier, we can use of Date and Calendar classes only.
1. Get Current Date and Time (Java 8 or Later)
1.1. Core Classes
In Java 8 or later, the date and time information is represented by the following classes. These classes provide the current date and time locally to the user, and there is no timezone information is associated with it.
-
– Represents the Date only information in yyyy-MM-dd pattern. – Represents the Time only information in HH:mm:ss.SSSSSSSSS pattern. – Represents the Date and Time informations, both, without any timezone information. The pattern is the combination of local date and time information.
To get the current date and time information in another timezone/locale, we can use the following classes.
-
– Represents the date and time information in a given timezone.
1.2. Code Examples
The following code shows how to get the current date-time information using the now() method in each class. The now() method returns an immutable and thread-safe instance of the class for which it is invoked.
To get the timezone-specific date and time information, pass the zone information in the ZonedDateTime.now() method.
1.3. Display Formatted Date and Time
To default string representations of the above classes are fixed. If we want to display the information in some custom pattern, we can use DateTimeFormatter class.
2. Get Current Date and Time (Java 7 or Earlier)
2.1. Core Classes
Till version 7 or earlier, Java didn’t have separate classes for the date and time parts. The main classes were :
- java.util.Date
- java.util.Calendar
2.2. Code Examples
Let us have a quick look at the methods used for getting the current date and time information in legacy Java classes.
2.3. Display Formatted Date and Time
To display, the date-time in a custom formatted manner, we should use SimpleDateFormat class.
How to Get Current Date and Time in Java
In this article, we'll explore many ways to Get the Current Date and Time in Java. Most applications have the need for timestamping events or showing date/times, among many other use-cases:
- When we publish blogs on a website, the date of posting gets written down into a database and shown to the reader.
- When we make an action, we'd want to know the time of it to be available so that we can keep track of them.
- When we buy something online or make a transaction, our banks offer us the transaction list with the exact timestamps for us to review.
Long story short, getting the current date and time in Java is very important and has a myriad of usages, and thankfully, it's really easy to attain it for any kind of use.
System.currentTimeMillis()
If you'd like to get a single numeric value of milliseconds passed since the UNIX epoch, it's as easy as:
Printing this value out would result in something similar to this:
When converting this number back to a human-readable date, it represents:
And to do this in Java, we need only a couple of lines of code:
Running this piece of code would yield:
Note: Keep in mind that this method returns the current value depending on your system time.
java.util.Date
In Java, getting the current date is as simple as instantiating the Date object from the Java package java.util :
We can format this date easily:
And running this piece of code would yield:
The Calendar API
Amongst Java's myriad of classes is the Calendar class, which is used to convert dates and time between specific instants and the calendar fields.
Getting the current date and time is really easy using a calendar:
Again, we can easily format this:
The getTime() method returns a Date object. Since SimpleDateFormat only works with Date objects, we're calling the getTime() method of the Calendar class to format it.
Running this piece of code would yield:
The Date/Time API
Java 8 introduced us to a whole new API, which was included in the build to replace java.util.Date and java.util.Calendar .
It's still useful to know how to get the current date and time using the previous two classes since not all applications have yet migrated to Java 8.
The Date/Time API provides multiple classes that we can rely on to get the job done:
LocalDate
LocalDate represents just a date, without time. This means that we can only get the current date, but without the time of the day:
This time around, instead of initializing a new object, we're calling the static method now() which returns the current date according to the system clock, with the default time-zone.
We can format this object:
Running this piece of code would yield:
You can also pass a ZoneId to the method to retrieve the date based on the specified time-zone, instead of the default one:
You can get a list of all available time-zone ID's via:
LocalTime
LocalTime is the opposite of LocalDate in that it represents only a time, without the date. This means that we can only get the current time of the day, without the actual date:
We can easily format this object:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Running this piece of code would yield:
LocalDateTime
And finally, a LocalDateTime , the most used Date/Time class in Java, represents the combination of the previous two — holding the value of both the date and the time:
We can easily format this object:
Running this piece of code would yield:
ZonedDateTime
Alongside the previous classes, the ZonedDateTime class also offers this functionality:
We can easily format this object:
Running this piece of code would yield:
Clock
Another class introduced to us in the Java 8 Date/Time API is the Clock class. It provides access to the current Instant , LocalDate , LocalTime and LocalDateTime using a time-zone.
That being said, using a Clock , you practically instantiate all of those and can access the ones you're interested in.
Through this object instance, we can instantiate many of the previously mentioned classes:
Note: It's valid to ask why we'd use a Clock instead of just leaving the now() method empty. A Clock is optional and the now() method typically uses the system's clock to determine the values. Though, through a clock you can have more than just your system's clock if you wish so. In our example, it doesn't make a difference, though.
Using the clock , we can extract an Instant :
Running this code would yield:
You can make a zoned Clock by passing a ZoneId to to Clock.system() :
Printing the value of the Instant belonging to clock would yield:
And finally, using a Clock , via the millis() method, you can access the millisecond value of the clock, which is the same as System.currentTimeMillis() :
Both of these will print out:
Joda-Time
Joda-Time is a tool that was originally developed to counter the problems with the old Java time and date classes.
With the release of Java 8, these problems have been tackled, and Joda-Time has served its purpose, without being used today very often.
Again, if your project isn't updated to Java 8, Joda-Time is still a great tool to use as an alternative.
To use it in your project, it's easiest to simply add a Maven dependency:
Working with Joda-Time is very similar to working with Java's Date/Time API:
Note: When initializing Joda-Time's DateTime class for the first time, there are known performance issues that occur due to the loading of chronology descriptors.
It's easy to format this object:
Running this piece of code would yield:
Conclusion
There are many cases where someone would need to get the current date and/or time in Java, and we've covered all approaches there are as of now to do so, including the older classes — java.util.Date and java.util.Calendar as well as the newer java.time classes that arrived with the new Date/Time API.
Additionally, we've covered Joda-Time and its approach to getting the current date and time.
If you'd like to read about Converting a String to a Date in Java, we've got it covered!