I am getting date and time from JSON API URL which format is like this
'2021-03-05 09:18:07' which is in String form.
but when I want to convert it in milliseconds it gives me an error of index 10. I don't know why this issue is coming I check other Stackoverflow answer but did not successed
DateTimeFormatter formatter ;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT);
String dates = object.getString("created_at");
long timeInMilliseconds = OffsetDateTime.parse(dates, formatter)
.toInstant()
.toEpochMilli();
System.out.println("Date in milli :: USING ThreeTenABP >>> " +
timeInMilliseconds);
}
String text = TimeAgo.using(timeInMilliseconds);
FeedModel.setDateSnap(text);
and here is error
java.time.format.DateTimeParseException: Text '2021-03-05 09:18:07' could not be parsed: Unable
to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2021-03-05T09:18:07 of type
java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.OffsetDateTime.parse(OffsetDateTime.java:396)
at com.example.wasigram.MainActivity$1.onResponse(MainActivity.java:91)
at com.androidnetworking.common.ANRequest.deliverSuccessResponse(ANRequest.java:729)
at com.androidnetworking.common.ANRequest.access$6500(ANRequest.java:80)
at com.androidnetworking.common.ANRequest$6.run(ANRequest.java:709)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.time.DateTimeException: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2021-03-05T09:18:07 of type java.time.format.Parsed
Using Java SE 8 API:
You can use
DateTimeFormatter#withZone
to get a formatter with the specified zone.Also, use the correct format,
yyyy-MM-dd HH:mm:ss
which does not have'T'
which you have put in your pattern by mistake. In fact, I prefer usingu
toy
as explained in this answer.Demo:
Output:
Learn more about the modern date-time API from Trail: Date Time.
Using ThreeTen-Backport API:
Output: