Tom G
Tom G

Reputation: 2655

Java simple Timestamp to Date conversion

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).

Upvotes: 7

Views: 26368

Answers (4)

Gelldur
Gelldur

Reputation: 11568

Use Time class form Google it is the best for this kind of job specialy it has good performance not like Calendar.

Upvotes: 0

felix fan
felix fan

Reputation: 21

int time = (int) (System.currentTimeMillis());

here you should use long instead of int.

Upvotes: 2

Paul Burke
Paul Burke

Reputation: 25584

This works:

final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Date date = cal.getTime();
mHour = date.getHours();
mMinute = date.getMinutes();

Upvotes: 9

Mark B
Mark B

Reputation: 201093

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.

Upvotes: 8

Related Questions