【问题标题】:Java - convert unix time in miliseconds with time zone to timestampJava - 将带有时区的unix时间(以毫秒为单位)转换为时间戳
【发布时间】:2019-03-03 01:16:58
【问题描述】:

我有一个字符串例如:

1517439600000+0100

我想将它转换为以毫秒为单位的 unix 时间,没有时区。 我该怎么做?

附言 1)我不能使用substring(0,5)并在字符串中添加3.6m毫秒,因为我有很多时区,曾经是+0100,然后是+0200等等......

2) 如果更容易转换为常规时间戳,如 YYYY-mm-dd hh:mm:ss 应该没问题的。

【问题讨论】:

  • 1517439600000+0100的格式是什么?
  • 当输入为1517439600000+0100时,期望的输出是什么?
  • 2018-FEB-01 00:00:00 和 UTC+1(UTC+2 将是 2018-FEB-01 01:00:00)

标签: java time timezone unix-timestamp converters


【解决方案1】:

你可以这样做:

    String sign = "+";
    String [] parts = time.split(sign);

    Long millis = Long.parseLong(parts[0]);
    String zoneOffset = sign + parts[1];

    LocalDate date = Instant.ofEpochMilli(millis).atZone(ZoneOffset.of(zoneOffset)).toLocalDate();

【讨论】:

    【解决方案2】:
        String exampleString = "1517439600000+0100";
        // Split string before + or-
        String[] parts = exampleString.split("(?=[+-])");
        if (parts.length != 2) {
            throw new IllegalArgumentException("Unexpected/unsupported format: " + exampleString);
        }
        // Parse the milliseconds into an Instant
        Instant timeStamp = Instant.ofEpochMilli(Long.parseLong(parts[0]));
        // Parse the offset into a ZoneOffset
        DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("xx");
        ZoneOffset offset = ZoneOffset.from(offsetFormatter.parse(parts[1]));
        // Combine
        OffsetDateTime dateTime = timeStamp.atOffset(offset);
        System.out.println(dateTime);
    

    输出:

    2018-02-01T00:00+01:00

    自纪元 (1 517 439 600 000) 以来的毫秒数表示独立于时区或偏移量的时间点。因此,为了获得时间戳,解析这个数字就足够了。如果您对 Instant(示例中为 2018-01-31T23:00:00Z)感到满意,您当然可以删除代码的后半部分。我的风格是在不需要立即获取所有信息时也从字符串中获取所有信息。

    我用于拆分的正则表达式(?=[+-]) 是一个正向预测:它匹配+- 之前的空字符串。匹配空字符串很重要,因此字符串的任何部分都不会在拆分中丢失(我们需要保留符号)。

    解析偏移量的更简单方法是ZoneOffset.of(parts[1])(正如 NiVeR 在另一个答案中所做的那样)。唯一的区别是我使用的DateTimeFormatter 还验证格式确实类似于+0100(无冒号)或Z

    【讨论】:

      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      • 2020-06-24
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多