java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. In Java (because this is what I can write):
ZoneId zone = ZoneId.of("Asia/Kolkata");
DateTimeFormatter uiDateFormatter = DateTimeFormatter.ofPattern("M/d/uuuu");
String isoF8601ormatDateTime = "2020-05-08T11:01:48.3300000Z";
Instant time = Instant.parse(isoF8601ormatDateTime);
String uiString = time.atZone(zone)
.format(uiDateFormatter);
System.out.println(uiString);
Output is:
5/8/2020
Points to note:
- The format from your API is ISO 8601. The classes of java.time parse the most common ISO 8601 variants as their default, that is, we need not specify any formatter.
- My code also converts the date to the user’s time zone before formatting. Most users will expect this. Please put your user’s time zone where I put Asia/Kolkata.
Bonus info: to format the time, in the user’s time zone too:
DateTimeFormatter uiTimeFormatter
= DateTimeFormatter.ofPattern("hh:mm:ss a", Locale.ENGLISH);
String uiTimeString = time.atZone(zone).format(uiTimeFormatter);
System.out.println(uiTimeString);
04:31:48 PM
What went wrong in your attemtps?
- There exists no way that
SimpleDateFormat
can parse 7 decimals on the seconds correctly. It only supports milliseconds, exactly three decimals. SimpleDateFormat
takes 3300000 to be milliseconds, that is 3300 seconds or nearly an hour, which it adds to the time parsed.
Z
in your incoming string is a UTC offset (of zero) and needs to be parsed as such, or you will get an incorrect result.
Z
without quotes will parse an offset like +0000
, but not Z
. XX
will parse Z
, but that attempt failed because you additionally required (one more) Z
after the Z
.
- You did not convert to the user’s time zone before formatting.
Links