开发者

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() an开发者_Go百科d 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).


This works:

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


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.


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

here you should use long instead of int.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜