Java:如何将UTC时间戳转换为本地时间?

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

  • 酷它实际上工作.我可以通过调用TimeZone.getDefault()来获取Android设备的默认时区. (6认同)

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.
  • 避免使用三个字母的时区缩写.它们不是标准化的,因此通常是模棱两可的.例如,PST可能意味着Philppine标准时间,太平洋标准时间或皮特凯恩标准时间(虽然缩写中的S通常用于夏季时间(意味着DST)).如果你想要太平洋标准时间,那甚至不是一个时区,因为在夏天(你的样本时间戳下降)使用太平洋夏令时代替.而不是缩写在我的代码中使用格式region/city中的时区ID .
  • 时间戳通常最好作为Instant对象处理.ZonedDateTime仅在您有需要时转换为演示文稿.

问题:我可以在Java版本中使用现代API吗?

如果至少使用Java 6,则可以.