3

I have strings like Thu Feb 04 21:25:12 CET 2021 and Sat Oct 03 11:57:00 CEST 2020 and I need to convert it to ISO_Instant time but my code doesn't work.

I hope someone can help me.

My Code:

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();
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Andre
  • 39
  • 1
  • 6
  • Related: (1) [Java String to Date, ParseException](https://stackoverflow.com/questions/7045931/java-string-to-date-parseexception) (2) [java DateTimeFormatterBuilder fails on testtime \[duplicate\]](https://stackoverflow.com/questions/50526234/java-datetimeformatterbuilder-fails-on-testtime) – Ole V.V. May 19 '21 at 13:06

1 Answers1

3

Your date-time string has timezone Id instead of timezone offset and therefore you should parse it into ZonedDateTime. Also, 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);
    }
}

Output:

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

Learn more about java.time, the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use 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 How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110