How to get the current date/time in Java
What's the best way to get the current date/time in Java?
It depends on what form of date / time you want:
If you want the date / time as a single numeric value, then
System.currentTimeMillis()gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java
long). This value is a delta from a UTC time-point, and is independent of the local time-zone ... assuming that the system clock has been set correctly.
If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:
new Date()gives you a
Dateobject initialized with the current date / time. The problem is that the
DateAPI methods are mostly flawed ... and deprecated.
Calendar.getInstance()gives you a
Calendarobject initialized with the current date / time, using the default
TimeZone. Other overloads allow you to use a specific
TimeZone. Calendar works ... but the APIs are still cumbersome.
new org.joda.time.DateTime()gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. Jodatime's LocalDateTime is slow when used the first time.)
in Java 8, calling
java.time.ZonedDateTime.now()will give you representations1 for the current date / time.
Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.
With Java 8 and later, the standard
java.time package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate.2.
1 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
2 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.
(Attention: only for use with Java versions <8. For Java 8+ check other replies.)
If you just need to output a time stamp in format YYYY.MM.DD-HH.MM.SS (very frequent case) then here's the way to do it:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
Read more... Read less...
If you want the current date as String, try this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date));
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime()));
Instant.now() // Capture the current moment in UTC, with a resolution of nanoseconds. Returns a `Instant` object.
… or …
ZonedDateTime.now( // Capture the current moment as seen in… ZoneId.of( "America/Montreal" ) // … the wall-clock time used by the people of a particular region (a time zone). ) // Returns a `ZonedDateTime` object.
A few of the Answers mention that java.time classes are the modern replacement for the troublesome old legacy date-time classes bundled with the earliest versions of Java. Below is a bit more information.
The other Answers fail to explain how a time zone is crucial in determining the current date and time. For any given moment, the date and the time vary around the globe by zone. For example, a few minutes after midnight is a new day in Paris France while still being “yesterday” in Montréal Québec.
Much of your business logic and data storage/exchange should be done in UTC, as a best practice.
To get the current moment in UTC with a resolution in nanoseconds, use
Instant class. Conventional computer hardware clocks are limited in their accuracy, so the current moment may be captured in milliseconds or microseconds rather than nanoseconds.
Instant instant = Instant.now();
ZoneId z = ZoneId.of( "America/Montreal" ); ZonedDateTime zdt = instant.atZone( z );
We can skip the
Instant and get the current
ZonedDateTime zdt = ZonedDateTime.now( z );
Always pass that optional time zone argument. If omitted, your JVM’s current default time zone is applied. The default can change at any moment, even during runtime. Do not subject your app to an externality out of your control. Always specify the desired/expected time zone.
ZonedDateTime do_Not_Do_This = ZonedDateTime.now(); // BAD - Never rely implicitly on the current default time zone.
You can later extract an
Instant from the
Instant instant = zdt.toInstant();
Always use an
ZonedDateTime rather than a
LocalDateTime when you want an actual moment on the timeline. The
Local… types purposely have no concept of time zone so they represent only a rough idea of a possible moment. To get an actual moment you must assign a time zone to transform the
Local… types into a
ZonedDateTime and thereby make it meaningful.
LocalDate class represents a date-only value without time-of-day and without time zone.
ZoneId z = ZoneId.of( "America/Montreal" ); LocalDate today = LocalDate.now( z ); // Always pass a time zone.
To generate a String representing the date-time value, simply call
toString on the java.time classes for the standard ISO 8601 formats.
String output = myLocalDate.toString(); // 2016-09-23
… or …
String output = zdt.toString(); // 2016-09-23T12:34:56.789+03:00[America/Montreal]
ZonedDateTime class extends the standard format by wisely appending the name of the time zone in square brackets.
For other formats, search Stack Overflow for many Questions and Answers on the
Contrary to the comment on the Question by RamanSB, you should not use
LocalDateTime class for the current date-time.
LocalDateTime purposely lacks any time zone or offset-from-UTC information. So, this is not appropriate when you are tracking a specific moment on the timeline. Certainly not appropriate for capturing the current moment.
LocalDateTime has only a date and a time-of-day such as "noon on 23rd of January 2020", but we have no idea if that is noon in Tokyo Japan or noon in Toledo Ohio US, two different moments many hours apart.
The “Local” wording is counter-intuitive. It means any locality rather than any one specific locality. For example Christmas this year starts at midnight on the 25th of December:
2017-12-25T00:00:00, to be represented as a
LocalDateTime. But this means midnight at various points around the globe at different times. Midnight happens first in Kiribati, later in New Zealand, hours more later in India, and so on, with several more hours passing before Christmas begins in France when the kids in Canada are still awaiting that day. Each one of these Christmas-start points would be represented as a separate
From outside your system
If you cannot trust your system clock, see Java: Get current Date and Time from Server not System clock and my Answer.
To harness an alternate supplier of the current moment, write a subclass of the abstract
You can pass your
Clock implementation as an argument to the various java.time methods. For example,
Instant.now( clock ).
Instant instant = Instant.now( yourClockGoesHere ) ;
For testing purposes, note the alternate implementations of
Clock available statically from
tick, and more.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
YearQuarter, and more.
Just create a Date object...
import java.util.Date; Date date = new Date();
// 2015/09/27 15:07:53 System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) ); // 15:07:53 System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) ); // 09/28/2015 System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime())); // 20150928_161823 System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) ); // Mon Sep 28 16:24:28 CEST 2015 System.out.println( Calendar.getInstance().getTime() ); // Mon Sep 28 16:24:51 CEST 2015 System.out.println( new Date(System.currentTimeMillis()) ); // Mon Sep 28 System.out.println( new Date().toString().substring(0, 10) ); // 2015-09-28 System.out.println( new java.sql.Date(System.currentTimeMillis()) ); // 14:32:26 Date d = new Date(); System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 ); // 2015-09-28 17:12:35.584 System.out.println( new Timestamp(System.currentTimeMillis()) ); // Java 8 // 2015-09-28T16:16:23.308+02:00[Europe/Belgrade] System.out.println( ZonedDateTime.now() ); // Mon, 28 Sep 2015 16:16:23 +0200 System.out.println( ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) ); // 2015-09-28 System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class // 16 System.out.println( LocalTime.now().getHour() ); // 2015-09-28T16:16:23.315 System.out.println( LocalDateTime.now() );