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

Leave a Comment

tech