Search code examples
javatimedate-conversion

Java Convert Time to iso_instant


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();

Solution

  • 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.