Parse unknown DateTime string with Time Zone identifier

Viewed 80

How can this string 20190612070000.000[-4:EDT] be parsed into ZonedDateTime?

I've tried this pattern and bunch of others, but nothing works so far:

String dateString = "20190612070000.000[-4:EDT]";

ZonedDateTime dateTime = ZonedDateTime.parse(dateString, ofPattern("yyyyMMddHHmmss.S[x:z]"));
1 Answers

There is no OOTB (Out-Of-The-Box) DateTimeFormatter with the pattern matching your date-time string. You can define one using DateTimeFormatterBuilder.

Demo:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                .appendPattern("uuuuMMddHHmmss.SSS")
                                .appendLiteral('[')                                
                                .appendOffset("+H", "")
                                .appendLiteral(':')
                                .appendZoneText(TextStyle.SHORT)
                                .appendLiteral(']')
                                .toFormatter(Locale.ENGLISH);
                                
        String strDateTime = "20190612070000.000[-4:EDT]";
        
        ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
        System.out.println(zdt);
    }
}

Output:

2019-06-12T07:00-04:00[America/New_York]

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.

Related