Java simple Timestamp to Date conversion

2019-01-24 12:32发布

问题:

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

回答1:

This works:

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


回答2:

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.



回答3:

Take a look of this.

Hope this is wat you need.

Android Simple Date Format

Good Luck!!



回答4:

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

here you should use long instead of int.



回答5:

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