Java 将时间转换为 iso_instant

Java Convert Time to iso_instant

我有 Thu Feb 04 21:25:12 CET 2021Sat Oct 03 11:57:00 CEST 2020 这样的字符串 我需要将其转换为 ISO_Instant 时间,但我的代码不起作用。

希望有人能帮助我。

我的代码:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz uuuu");
Instant ist = OffsetDateTime.parse("Thu Feb 04 19:03:27 CET 2021", dtf).toInstant();

您的日期时间字符串具有时区 ID 而不是时区偏移量,因此您应该将其解析为 ZonedDateTime。另外,Never use SimpleDateFormat or DateTimeFormatter without a Locale.

import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz uuuu", Locale.ENGLISH);

        Instant instant = ZonedDateTime.parse("Thu Feb 04 19:03:27 CET 2021", dtf).toInstant();
        System.out.println(instant);

        instant = ZonedDateTime.parse("Sat Oct 03 11:57:00 CEST 2020", dtf).toInstant();
        System.out.println(instant);
    }
}

输出:

2021-02-04T18:03:27Z
2020-10-03T09:57:00Z

详细了解 java.timemodern date-time API* from Trail: Date Time


* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and