Java简单的时间戳与日期转换

7

我一直在尝试寻找答案,但今天有太多矛盾的信息......

我想在Android中获取当前Unix时间戳,然后将其转换为允许我获取小时和分钟的格式。

我目前正在执行以下操作:

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

但是它没有给我正确的小时或分钟值(对于当前东海岸时间13:33,它返回03:38)。

4个回答

9

这个有效:

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

这样做会返回一个时间为07:00。难道是我的设备系统时间出了问题吗? - Tom G
1
好的,明白了。我之前把时间戳存成了int类型,但实际上应该是Long类型。谢谢大家。 - Tom G
6
在安卓系统中,date.getHours、date.getMinutes等方法已经被弃用了。请使用@mbaird提供的解决方案。 - Lior Iluz

8

使用Java的Calendar类即可。

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

请注意,您的Android模拟器将以格林威治标准时间返回当前时间。建议在真实设备上测试此类代码。


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

在这里,您应该使用long而不是int


0

使用来自谷歌的Time类,它是这种工作的最佳选择,特别是它具有良好的性能,不像日历。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接