我有一个 UTC 时间戳,我想将其转换为本地时间,而不使用像 TimeZone.getTimeZone("PST")
这样的 API 调用。你到底应该怎么做?我一直在使用以下代码,但没有取得多大成功:
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]
应该返回相当于 [2012-08-15T15:56:02.038Z]
最佳答案
Date
没有时区,内部存储为 UTC。只有当日期被格式化时,时区更正才适用。使用 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));
这打印出 2012-08-15T15:56:02.038
请注意,我在 PST 格式中省略了 'Z'
,因为它表示 UTC。如果你只是使用 Z
那么输出将是 2012-08-15T15:56:02.038-0700
关于Java:如何将 UTC 时间戳转换为本地时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12487125/