Search code examples
javadatedatetimesimpledateformat

Java SimpleDateFormat can not parse date in "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSX" format pattern


I have simple code, which parses string into date.

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSX").parse("2021-06-28T07:09:30.463931900Z")

It parses this string into Sat Jul 03 18:01:41 CEST 2021, which is not valid.

When I remove from pattern 'SSSSSSSSSX', it starts working and returns: Mon Jun 28 07:09:30 CEST 2021.

Problem is that I need nanoseconds, so I can not just get rid of this.

I found many similar topics, but any of them dealt with such date format.


Solution

  • Use java.time:

    You can parse this example String without any explicit pattern, keep the precision as desired and, if necessary, format those date and time values in a multitude of custom ways.

    Here's a small example:

    public static void main(String[] args) {
        // example String (of ISO format)
        String input = "2021-06-28T07:09:30.463931900Z";
        // parse it (using a standard format implicitly)
        OffsetDateTime odt = OffsetDateTime.parse(input);
        // print the result
        System.out.println(odt);
        
        // if you want a different output, define a formatter
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
                // use a desired pattern
                "EEE MMM dd HH:mm:ss O uuuu",
                // and a desired locale (important for names)
                Locale.ENGLISH);
        // print that
        System.out.println(odt.format(dtf));
    }
    

    This code example produces the following output:

    2021-06-28T07:09:30.463931900Z
    Mon Jun 28 07:09:30 GMT 2021