2021-04-05t16:25:45.000+00:00 Time Stamp Change In Simpledateformat("yyyy-mm-dd Hh:mm:ss A")
Solution 1:
java.time through desugaring
Consider using java.time, the modern Java date and time API, for your date and time work. Use for example this output formatter:
privatestaticfinalDateTimeFormatterOUTPUT_FORMATTER= DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a", Locale.forLanguageTag("en-IN"));
With it do:
Stringdate = "2021-04-05T16:25:45.000+00:00";
OffsetDateTime dateTime = OffsetDateTime.parse(date);
String formattedDate = dateTime.format(OUTPUT_FORMATTER);
System.out.println(formattedDate);
Output:
2021-04-05 04:25:45 PM
You may use a different locale for the output formatter as appropriate for your requirements. The choice of locale determines which strings are used for AM and PM.
I am exploiting the fact that the string that you have got is in ISO 8601 format. offsetDateTime
parses this format as its default, that is, without any explicit formatter.
What went wrong in your code?
You tried using a format pattern string of yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
for a date string of 2021-04-05T16:25:45.000+00:00
. The 'Z'
in single quotes in the format pattern string means that your date string must end in a literal Z
. When instead it ended in +00:00
, parsing failed with a ParseException
. If you didn’t see the output from e.printStackTrace();
in your code, you have got a serious flaw in your project setup that you should fix before worrying about how to parse the date string. In any case, since parsing failed, parsedDate
kept its initial value of null
, which caused outputFormat.format(parsedDate)
to throw the NullPointerException
that you did see.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links
- Oracle tutorial: Date Time explaining how to use java.time.
- Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - Java 8+ APIs available through desugaring
- ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
- Wikipedia article: ISO 8601
Post a Comment for "2021-04-05t16:25:45.000+00:00 Time Stamp Change In Simpledateformat("yyyy-mm-dd Hh:mm:ss A")"