Rarw
Rarw

Reputation: 7663

Calendar getTimeInMills = July 4, 46452?

I am using Calendar on a Samsung Note. If I get a new instance of Calendar with Calendar.getInstance() and then call getTimeInMills() without doing anything else I get 1403732346277, which apparently is some value in the very far future.

I need to get a unix style timestamp. Is there some other preferred way to do this? Or some reason why the Calendar is returning this value (i.e. a standard adjustment I can make)?

Upvotes: 1

Views: 127

Answers (3)

JDJ
JDJ

Reputation: 4328

Or some reason why the Calendar is returning this value (i.e. a standard adjustment I can make)?

The java.util.Calendar API stores dates and times as the number of milliseconds that have elapsed from epoch (January 1, 1970 midnight UTC).

The number you got from Calendar.getInstance() - 1403732346277 - is what you'd expect. It's the number of milliseconds from epoch up to today at the exact time you called Calendar.getInstance().

If you want to extract more human-readable date/time information from that Calendar object, you can do something like:

Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);

I need to get a unix style timestamp. Is there some other preferred way to do this?

As this post points out, you can get UNIX epoch by:

long unixTime = System.currentTimeMillis() / 1000L;

Upvotes: 0

Yogendra Singh
Yogendra Singh

Reputation: 34367

getTimeInMillis() returns you the time difference from Jan 1, 1970 with the calendar time in milliseconds.

Here is the calculation:

1403732346277 ms = 1403732346.277 seconds

1403732346.277 s = 389925.6517... hours

389925.6517 h = 16246.90 days

16246.90 days = 44.512 years (simple calculation: I divided by 365 just to get an approx idea. There are leap years in between.)

If you find the difference of current date from Jan 1, 1970, it is 44 years and ~6 months. So it seems to be giving you right time in milliseconds.

Upvotes: 1

Robby Cornelissen
Robby Cornelissen

Reputation: 97152

Unix time represents the number of seconds from the epoch. As the name implies, getTimeInMillis() will return the number of milliseconds from the epoch. You need to divide your milliseconds by 1000 to get unix time.

long unixTime = Calendar.getInstance().getTimeInMillis() / 1000;

Upvotes: 2

Related Questions