-1

I have this date/time value 2020-02-29T18:21:13.2627230Z that I am trying to parse using SimpleDateFormat Class. I used several patterns because I don't which to use:

yyyy-MM-dd'T'HH:mm:ss.SSS'Z' => Time parsed is: Sat Feb 29 19:05:00 UTC 2020

yyyy-MM-dd'T'HH:mm:ssss => Time parsed is: Sat Feb 29 18:21:13 UTC 2020

yyyy-MM-dd'T'HH:mm:ss.SSS => Time parsed is: Sat Feb 29 19:05:00 UTC 2020

What does the last part mean 2627230Z. Are the digits here the milliseconds and Z the time in UTC? if so, shouldn't I use the pattern that ends with SSSSSSSZ ? I'm getting a parseException here.

Also why am I getting a different output in the minutes 19:05:00 (1st pattern) and 18:21:13 (2nd pattern)

Thanks

Steve
  • 81
  • 1
  • 7

2 Answers2

1

Use ZonedDateTime from the java::time package. You can then further modify it by changing zones or time offsets. The other date packaged like Date and Calendar are obsolete.

    String s = "2020-02-29T18:21:13.2627230Z";
        ZonedDateTime zdt = ZonedDateTime.parse(s);
        System.out.println(zdt);

Prints

2020-02-29T18:21:13.262723Z

To find out what those values mean and others, check out the DateTimeFormatter class. It explains everything you want to know.

WJS
  • 36,363
  • 4
  • 24
  • 39
1

The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. I suggest you should stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.

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.

Using the modern date-time API:

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.parse("2020-02-29T18:21:13.2627230Z");
        System.out.println(instant);

        System.out.println(instant.getNano());
    }
}

Output:

2020-02-29T18:21:13.262723Z
262723000

What does the last part mean 2627230Z. Are the digits here the milliseconds and Z the time in UTC?

It is nanoseconds and Z stands for Zulu i.e. date-time at UTC.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110