Monday 31 October 2016

datetime - How to get the current date/time in Java



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


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 LocalDateTime.now() and 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, this is no longer true. However, if you are already using Joda time in your codebase, there is no strong2 reason to migrate.






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 - Your code won't break if you don't, and you won't get deprecation warnings. Sure, the Joda codebase will probably stop getting updates, but it is unlikely to need them. No updates means stability and that is a good thing. Also note that it is highly likely that if that someone will fix problems caused by regressions in the Java platform.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...