Reputation: 21
When we call parseJavaAndroid("2018-04-27T22:31:07.962-05:00")
from JVM it gives ParseException
while a call from Emulator/Android Real device it works fine.
When we change SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", Locale.ENGLISH)
to SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH)
in Android, it throws:
IllegalArgumentException with message "Unknown pattern character 'X' method".
It works fine in JVM and gives ParseException
in Emulator/Android Real device.
public static Date parseJavaAndroid(String fromDate){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", Locale.ENGLISH);
Date date=null;
try {
date = format.parse(fromDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
What should have to do then it works in both JVM and android real time device(minSdkVersion:19). I want pattern for "2018-04-27T22:31:07.962-05:00" which works on both Android as well as Java.
Note: The individual pattern is working, so Please don't suggest for individuals.
Upvotes: 0
Views: 261
Reputation: 48
I can't tell about Android, but in the JVM, the Z
pattern recognizes only offsets without :
, such as -0500
, while the X
pattern can recognize -05:00
: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Perhaps Android has a different implementation, where Z
also recognizes offsets with :
, such as -05:00
.
I'm afraid there's no one-pattern-fits-all solution: Z
doesn't work in JVM, X
doesn't work in Android, how to make it work in both? I think the best you can do is to try both patterns, something like this (in pseudocode):
try {
parse with X
} catch(Exception e) {
X didn't work, parse with Z
}
A much better alternative is to use the threeten backport and configure with ThreetenABP - or use java.time
classes if your API level is 26:
// parse input
OffsetDateTime odt = OffsetDateTime.parse("2018-04-27T22:31:07.962-05:00");
// convert to java.util.Date (threeten backport)
Date date = DateTimeUtils.toDate(odt.toInstant());
// or, if you have java.time (API level 26)
Date date = date.from(odt.toInstant());
Upvotes: 1
Reputation: 3691
And according to your example and the android doc, you should use X
(ISO8601) instead of Z
(RFC822)
That gives: "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
Upvotes: 0