EugeneMi
EugeneMi

Reputation: 3575

Why use calendar.getTimeInMillis to get unix timestamps instead of Date.getTime

I saw code that does this:

long getTime(Date value){
     Calendar calendar = Calendar.getInstance(UTC);
     calendar.setTime(value);
     long unixMillis = calendar.getTimeInMillis();
     return unixMillis; 
 }

What's the point of using calendar.getTimeInMillis instead of value.getTime()?

Upvotes: 1

Views: 1230

Answers (2)

Luca Poddigue
Luca Poddigue

Reputation: 1082

There's nothing wrong in calling getTime() from the Date instance. Date has actually some deprecated methods, as well as all its parametrized constructors. The official documentation suggeststo use Calendar if you care about internationalization. As per the official docs

A Calendar object can produce all the calendar field values needed to implement the date-time formatting for a particular language and calendar style (for example, Japanese-Gregorian, Japanese-Traditional).

Take, for instance, the method getFirstDayOfWeek(). It will return an integer corresponding to SUNDAY (also defined as a constant in Calendar), in the U.S., and MONDAY in France.

There are a number of variations like this in the Calendar according to your current locale. Calendar allows you to take account of these, while Date offers limited support. Which class you would choose really depends on your application's needs.

Upvotes: 2

NoddySevens
NoddySevens

Reputation: 94

They are very similar in that they return the time in milliseconds from Epoch. The key difference is that Date.getTime() is measured in UT(Universal time). The method Calender.getTimeInMillis() is based on UTC which is universal time measured with an atomic clock includes leap seconds.

This makes the Calender.getTimeInMillis() method more precise.

Check these out for more information: https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime() https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getTimeInMillis()

Upvotes: 0

Related Questions