如何在Java中将UTC时间戳转换为本地日期,小时,分钟? [英] How to convert a UTC timestamp to local day, hour, minute in Java?

查看:511
本文介绍了如何在Java中将UTC时间戳转换为本地日期,小时,分钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

然后给出时间戳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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆