Java的:你如何转换UTC时间戳为本地时间? [英] Java: How do you convert a UTC timestamp to local time?
问题描述
我有一个时间戳是UTC中,我想将其转换为本地时间,而无需使用像TimeZone.getTimeZone(PST)API调用。到底是如何,你应该这样做吗?我一直在使用下面的code没有成功:
I have a timestamp that's in UTC and I want to convert it to local time without using an API call like TimeZone.getTimeZone("PST"). How exactly are you supposed to do this? I've been using the following code without much success:
private static final SimpleDateFormat mSegmentStartTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(mSegmentStartTimeFormatter.parse(startTime));
}
catch (ParseException e) {
e.printStackTrace();
}
return calendar.getTimeInMillis();
样的输入值:[2012-08-15T22:56:02.038Z]
Sample input value: [2012-08-15T22:56:02.038Z]
应该返回相当于[2012-08-15T15:56:02.038Z]
should return the equivalent of [2012-08-15T15:56:02.038Z]
推荐答案
日期
在UTC没有时区和内部商店。只有当一个日期格式是时区校正应用于。当使用日期格式
,则默认为它在运行JVM的时区,使用 setTimeZone
来根据需要对其进行修改
Date
has no timezone and internally stores in UTC. Only when a date is formatted is the timezone correction applies. When using a DateFormat
, it defaults to the timezone of the JVM it's running in. Use setTimeZone
to change it as necessary.
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = utcFormat.parse("2012-08-15T22:56:02.038Z");
DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
pstFormat.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(pstFormat.format(date));
这版画 2012-08-15T15:56:02.038
请注意,我在PST格式冷落的'Z'
,因为它表明UTC。如果你只是用以Z
去那么输出将是 2012-08-15T15:56:02.038-0700
Note that I left out the 'Z'
in the PST format as it indicates UTC. If you just went with Z
then the output would be 2012-08-15T15:56:02.038-0700
这篇关于Java的:你如何转换UTC时间戳为本地时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!