0

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.

gorrch
  • 521
  • 3
  • 16
  • 3
    All answers I see indicate that this is not possible with SimpleDateFormat. You'll need to implement your own formatter to accept this input string, but as mentioned in the above question's answer, Date will automatically reduce your nanoseconds down to milliseconds, so you'd likely need a custom solution for that as well. – Liftoff Jun 28 '21 at 07:51
  • 1
    @David You are correct that it is not possible with `SimpleDateFormat`. Furthermore it is not possible with `Date`, the type that `SimpleDateFormat` returns, since `Date` only has got millisecond precision. – Ole V.V. Jun 28 '21 at 09:07
  • 1
    Thanks guys. I used OffsetDatetime and then toInstant in order to use Duration.between two dates. – gorrch Jun 28 '21 at 09:09
  • You may also use `Duration.between(oneOffsetDateTime, anotherOffsetDateTime)` without converting to `Instant` first. – Ole V.V. Jun 28 '21 at 18:36

1 Answers1

3

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
deHaar
  • 17,687
  • 10
  • 38
  • 51