TheLettuceMaster
TheLettuceMaster

Reputation: 15734

Getting 0 Month with Current Timestamp in Java

Here is my code:

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(sp.timestamp);
    int month = cal.get(Calendar.MONTH);

When I do this,

Log.d("month", String.valueOf(month));

I get 0.

I also Logged the sp.timestamp and it is 1410460389. I am expecting to return "8" (as it is September). There are only three lines and they look correct so I am completely at a loss with this?

Upvotes: 2

Views: 80

Answers (3)

Rafael Lins
Rafael Lins

Reputation: 497

Month is 0-based, that's why it's zero. Here's Calendar's javadoc about it: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#MONTH

Upvotes: 0

M A
M A

Reputation: 72854

1410460389 corresponds to January 17, 1970. The first month starts with a zero.

The current timestamp should be 1410469839296 which shows your timestamp is actually in seconds instead of milliseconds.

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53829

1410460389 is in seconds while setTimeInMillis requires milliseconds.

Therefore, try:

cal.setTimeInMillis(sp.timestamp * 1000L);

Upvotes: 3

Related Questions