将毫秒转换为 java 具有偏移小时数 (Z05:00) 的日期

convert milliseconds to java date with offset hours (Z05:00)

如何将以毫秒为单位的字符串值转换为"2006-01-02T15:04:05Z07:00"日期格式的字符串? (包括 Z 偏移量)

编辑:您的字符串是占位符字符串

我相信 "2006-01-02T15:04:05Z07:00" 是 Golang 指定日期时间格式的方式。更准确地说是 ISO 8601 格式。实际格式化的字符串类似于 2018-09-19T00:26:42-05:00。所以使用 DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX") 或只是 DatetimeFormatter.ISO_OFFSET_DATE_TIME (并且在格式化程序格式化字符串后没有替换)。

原回答

这分为两个步骤:

  1. 将您的毫秒字符串(我假设从 1970-01-01 开始)转换为 Instant.
  2. Instant 转换为所需的时区并设置格式。

挑战在于第二步。偏移量有正负号,偏移量的标准格式化选项包括 -+(除了偏移量零有时被写为没有符号的 Z)。这是我对整个事情的看法:

    ZoneId zone = ZoneId.of("America/Denver");
    DateTimeFormatter firstShotFormatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss'Z'xxx");

    String milliseconds = "1136239445000";

    Instant pointInTime = Instant.ofEpochMilli(Long.parseLong(milliseconds));
    String firstShot = pointInTime.atZone(zone).format(firstShotFormatter);
    // Offset should be negative
    if (firstShot.contains("Z-")) {
        // Remove minus sign from formatted offset
        String result = firstShot.replace("Z-", "Z");
        System.out.println("Formatted string: " + result);
    } else {
        throw new IllegalStateException(
                "Don’t know how to format a positive offset from UTC");
    }

此片段的输出是:

Formatted string: 2006-01-02T15:04:05Z07:00

我初步猜测您的 Z07:00 偏移量指的是北美山区时间,即一月份的偏移量 -07:00。请检查。我不知道如何处理正偏移,所以我的代码检查它不会发生。

我发现你要求的格式很奇怪。它与 ISO 8601 具有日期和时间部分之间的特征 T。但据我所知,ISO 8601 的偏移量为 either Z (零)or 签名,例如 -07:00,绝不是这些的混合体。您可能想检查是否可以说服格式化字符串的接收者接受直接的 ISO 8601 字符串。我会发现这更清晰,最终更容易让各方理解。

链接