2

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]"));
edward_wong
  • 442
  • 7
  • 21

1 Answers1

3

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 1
    Hi Arvind, What did you mean by `+H`, I got *Invalid zone offset pattern: +H* Java8 – Youcef LAIDANI May 17 '21 at 15:27
  • @YCF_L - `+H` is for zone offset hours. Please check this [online demo](https://ideone.com/6fpjxs). – Arvind Kumar Avinash May 17 '21 at 15:28
  • 1
    I think this should work with Java9+ not with Java8 check this comment of [Ole V.V.](https://stackoverflow.com/questions/64064664/java-datetimeformatter-parsing-with-special-characters#comment113291241_64065884) – Youcef LAIDANI May 17 '21 at 15:30