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 Javalong
). 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 aDate
object initialized with the current date / time. The problem is that theDate
API methods are mostly flawed ... and deprecated.Calendar.getInstance()
gives you aCalendar
object initialized with the current date / time, using the defaultLocale
andTimeZone
. Other overloads allow you to use a specificLocale
and/orTimeZone
. 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()
andZonedDateTime.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