在 Java 中将 ISO 8601 时间戳字符串转换为纪元秒

Hoy*_*der -2 java iso8601 epoch seconds unix-timestamp

我收到一个 ISO 8601 日期时间格式的字符串2020-11-03T15:23:24.388Z。在 Java 中将其转换为纪元秒的最佳方法是什么?

Arv*_*ash 5

使用现代日期时间 API,您可以按如下所示进行操作:

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.parse("2020-11-03T15:23:24.388Z");
        long seconds = instant.getEpochSecond();
        System.out.println(seconds);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

1604417004
Run Code Online (Sandbox Code Playgroud)

如果您正在为您的 Android 项目执行此操作,并且您的 Android API 级别仍然不符合 Java-8,请查看通过脱糖可用的 Java 8+ API如何在 Android 项目中使用 ThreeTenABP

Trail: Date Time 中了解有关现代日期时间 API 的更多信息。