Advertisement
Advertisement


How to get the current date/time in Java


Question

What's the best way to get the current date/time in Java?

2018/05/03
1
716
5/3/2018 5:44:17 AM

Accepted Answer

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 Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.

    • Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or 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.LocalDateTime.now() and 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.

2020/02/21
680
2/21/2020 4:29:57 AM


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));

or

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

2014/07/09

In Java 8 it is:

LocalDateTime.now()

and in case you need time zone info:

ZonedDateTime.now()

and in case you want to print fancy formatted string:

System.out.println(ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME))
2014/10/06

tl;dr

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.

java.time

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.

enter image description here

Time zone

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.

Instant

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

ZonedDateTime

You can adjust that Instant into other time zones. Apply a ZoneId object to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

We can skip the Instant and get the current ZonedDateTime directly.

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 ZonedDateTime.

Instant instant = zdt.toInstant();

Always use an Instant or 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

The 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.

Strings

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]

The 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 DateTimeFormatter class.

Avoid LocalDateTime

Contrary to the comment on the Question by RamanSB, you should not use LocalDateTime class for the current date-time.

The 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.

A 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 ZonedDateTime.


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.

photo of a couple of external radio clock devices

java.time.Clock

To harness an alternate supplier of the current moment, write a subclass of the abstract java.time.Clock class.

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 Clock itself: fixed, offset, tick, and more.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

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 Interval, YearWeek, YearQuarter, and more.

2019/10/10

Just create a Date object...

import java.util.Date;

Date date = new Date();
2020/04/30

    // 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() );
2015/09/28

Source: https://stackoverflow.com/questions/5175728
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]