And*_*oob 33 java api timezone calendar date
我有一个UTC时间戳,我想将它转换为本地时间而不使用像API这样的API调用TimeZone.getTimeZone("PST").你到底应该怎么做?我一直在使用以下代码但没有取得多大成功:
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();
Run Code Online (Sandbox Code Playgroud)
样本输入值: [2012-08-15T22:56:02.038Z]
应该返回相当于 [2012-08-15T15:56:02.038Z]
Ste*_*Kuo 54
Date在UTC中没有时区和内部存储.仅在格式化日期时才适用时区校正.使用a时DateFormat,它默认为运行它的JVM的时区.用于setTimeZone根据需要进行更改.
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));
Run Code Online (Sandbox Code Playgroud)
这打印 2012-08-15T15:56:02.038
请注意,我遗漏了'Z'PST格式,因为它表示UTC.如果你只是去了,Z那么输出就是2012-08-15T15:56:02.038-0700
Ole*_*.V. 14
使用现代Java日期和时间API,这很简单:
String inputValue = "2012-08-15T22:56:02.038Z";
Instant timestamp = Instant.parse(inputValue);
ZonedDateTime losAngelesTime = timestamp.atZone(ZoneId.of("America/Los_Angeles"));
System.out.println(losAngelesTime);
Run Code Online (Sandbox Code Playgroud)
这打印
2012-08-15T15:56:02.038-07:00[America/Los_Angeles]
Run Code Online (Sandbox Code Playgroud)
注意事项:
Z您的时间戳指UTC,也称为祖鲁时间.所以在你当地的时间价值,不Z应该在那里.相反,你会想要一个返回值,例如2012-08-15T15:56:02.038-07:00,因为偏移现在是-7小时而不是Z.Instant对象处理.ZonedDateTime仅在您有需要时转换为演示文稿.问题:我可以在Java版本中使用现代API吗?
如果至少使用Java 6,则可以.