Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current date/time in Java [duplicate]

Tags:

java

datetime

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

like image 814
user496949 Avatar asked Mar 03 '11 01:03

user496949


People also ask

How do you find the current date and time?

The Clock. systemUTC(). instant() method returns the current date and time both.

How do you call today's date in Java?

Code To Get Today's date in any specific FormatgetTime(); String todaysdate = dateFormat. format(date); System. out. println("Today's date : " + todaysdate);


4 Answers

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

  • 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. https://stackoverflow.com/questions/6280829.)

    • in Java 8, calling java.time.LocalDateTime.now() and java.time.ZonedDateTime.now() will give you representations2 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.3.


1 - System.currentTimeMillis() gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.
2 - 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."
3 - 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.

like image 54
Stephen C Avatar answered Oct 13 '22 10:10

Stephen C


(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());
like image 21
Liebster Kamerad Avatar answered Oct 13 '22 11:10

Liebster Kamerad


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/

like image 115
duggu Avatar answered Oct 13 '22 10:10

duggu


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?

  • 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.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.

like image 100
Basil Bourque Avatar answered Oct 13 '22 11:10

Basil Bourque