Get current time in Java

http://stackoverflow.com/questions/5175728/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-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.

People who know about these things recommend Joda-time as having (by far) the best APIs for doing things involving time point and duration calculations.

So the easiest way is System.currentTimeMillis() or System.nanoTime(), and they said nanoTime is more precise.

Get current time in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s