views:

204

answers:

2

I've been trying to find the answer to this for a while today and there's just so much contradictory information....

What I'd like to do is get a current unix timestamp in android, and then convert it to a format that allows me to getHours() and getMinutes().

I'm currently doing this:

int time = (int) (System.currentTimeMillis());
Timestamp ts = new Timestamp(time);
mHour = ts.getHours();
mMinute = ts.getMinutes();

But it's not giving me a correct value for hour or minute (it's returning 03:38 for the current East-coast time of 13:33).

A: 

Just use the Java Calendar class.

Calendar c = new GregorianCalendar();  // This creates a Calendar instance with the current time
mHour = c.get(Calendar.HOUR);
mMinute = c.get(Calendar.MINUTE);

Also note that your Android emulator will return times in GMT for the current time. I advise testing this type of code on a real device.

mbaird
A: 

This works:

final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Date date = cal.getTime();
mHour = date.getHours();
mMinute = date.getMinutes();
iPaulPro
Doing this returns a time of 07:00. Is it just that my device's system time is screwed up?
Tom G
OK, got it. I was storing the timestamp in an int, when it really has to be a Long. Thanks guys
Tom G