如何在Java中将UTC时间戳转换为本地日期,小时,分钟? [英] How to convert a UTC timestamp to local day, hour, minute in Java?
问题描述
然后给出时间戳1245613885,这是GMT中的时间戳
Given then timestamp 1245613885 that is a timestamp in GMT
如何使用服务器的本地时区信息将其转换为Java中的Year,Day,hour,Minute值?
How do I turn that into Year, Day, Hour, Minute values in Java using the server's local timezone info?
推荐答案
您可以使用 java.util.Calendar
。它提供了 setTimeZone()
方法(这是多余的,因为默认情况下它已经选择了系统默认时区)。
You can use java.util.Calendar
for this. It offers a setTimeZone()
method (which is by the way superfluous since it by default already picks the system default timezone).
long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
如果您想将其显示在易于理解的日期字符串中,那么我建议< a href = http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html rel = noreferrer> SimpleDateFormat
。
If you'd like to present it in a human readable date string, then I'd suggest SimpleDateFormat
for this.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25
(输出正确为每个我的时区GMT-4)
这篇关于如何在Java中将UTC时间戳转换为本地日期,小时,分钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!