How to Get Current Date and Time in Java

Introduction

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:

System.currentTimeMillis();

Printing this value out would result in something similar to this:

1580897313933

When converting this number back to a human-readable date, it represents:

Wednesday, 5 February 2020 10:08:33.933

And to do this in Java, we need only a couple of lines of code:

SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
System.out.println(formatter.format(date));

Running this piece of code would yield:

2020-02-05 at 10:11:33 UTC

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:

Date date = new Date(); // This object contains the current date value

We can format this date easily:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
System.out.println(formatter.format(date));

And running this piece of code would yield:

05-02-2020 10:12:46

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:

Calendar calendar = Calendar.getInstance(); // Returns instance with current date and time set

Again, we can easily format this:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
System.out.println(formatter.format(calendar.getTime()));

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:

25-11-2018 00:43:39

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:

LocalDate date = LocalDate.now(); // Gets the current date

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:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
System.out.println(date.format(formatter));

Running this piece of code would yield:

05-02-2020

You can also pass a ZoneId to the method to retrieve the date based on the specified time-zone, instead of the default one:

LocalDate date = LocalDate.now(ZoneId.of("Europe/Paris")); // Gets current date in Paris

You can get a list of all available time-zone ID's via:

System.out.println(ZoneId.getAvailableZoneIds());

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:

LocalTime time = LocalTime.now(); // Gets the current time

We can easily format this object:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(time.format(formatter));
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:

00:55:58

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:

LocalDateTime dateTime = LocalDateTime.now(); // Gets the current date and time

We can easily format this object:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
System.out.println(dateTime.format(formatter));

Running this piece of code would yield:

05-02-2020 10:31:42

ZonedDateTime

Alongside the previous classes, the ZonedDateTime class also offers this functionality:

ZonedDateTime dateTime = ZonedDateTime.now(); // Gets the current date and time, with your default time-zone

We can easily format this object:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
System.out.println(dateTime.format(formatter));

Running this piece of code would yield:

05-02-2020 10:32:26

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.

// Clock with the system's default timezone
Clock clock = Clock.systemDefaultZone();

// Clock with the UTC timezone
Clock clock = Clock.systemUTC();

Through this object instance, we can instantiate many of the previously mentioned classes:

// Each of these obtain the current instance of that class from the clock
LocalDateTime localDateTime = LocalDateTime.now(clock);
LocalTime localTime = LocalTime.now(clock);
LocalDate localDate = LocalDate.now(clock);
Instant instant = Instant.now(clock);
ZonedDateTime zonedDateTime.now(clock);

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:

Instant instant = clock.instant();
System.out.println(instant);

Running this code would yield:

2020-04-16T17:05:43.867063Z

You can make a zoned Clock by passing a ZoneId to to Clock.system():

Clock clock = Clock.system(ZoneId.of("Europe/Paris"));

Printing the value of the Instant belonging to clock would yield:

2020-04-16T17:08:16.139183Z

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():

System.out.println(clock.millis());
System.out.println(System.currentTimeMillis());

Both of these will print out:

1587057153329
1587057153329

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:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>${version}</version>
</dependency>

Working with Joda-Time is very similar to working with Java's Date/Time API:

DateTime dateTime = new DateTime(); // Initializes with the current date and time

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:

DateTimeFormatter formatter = DateTimeFormatter.forPattern("dd-MM-yyyy HH:mm:ss");
System.out.println(fmt.print(dateTime));

Running this piece of code would yield:

05-02-2020 10:33:05

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!

Last Updated: April 16th, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms