I'm getting an unparseable date exception using:
"2021-07-20T12:35:20-07:00".toDate()!!
@SuppressLint("SimpleDateFormat")
fun String.toDate() : Date? {
return SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(this)
}
I'm getting an unparseable date exception using:
"2021-07-20T12:35:20-07:00".toDate()!!
@SuppressLint("SimpleDateFormat")
fun String.toDate() : Date? {
return SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(this)
}
From the SimpleDateFormat
docs
Z Time zone RFC 822 time zone -0800 X Time zone ISO 8601 time zone -08; -0800; -08:00
The Z
directive expects the time zone to be specified without a colon, whereas X
allows a colon. Either format your dates like
2021-07-20T12:35:20-0700
or use the ISO 8601 timezone designator, rather than the RFC 822 one
yyyy-MM-dd'T'HH:mm:ssX
I recommend that you uses java.time, the modern Java date and time API, for your date and time work. Excuse my Java syntax:
public static OffsetDateTime toDate(String s) {
return OffsetDateTime.parse(s);
}
Let’s try it:
OffsetDateTime dateTime = toDate("2021-07-20T12:35:20-07:00");
System.out.println(dateTime);
Output is:
2021-07-20T12:35:20-07:00
We do not need to specify any formatter at all. Your string is in ISO 8601 format. OffsetDateTime
and the other classes of java.time parse the most common variants of ISO 8601 as their default, that is, without any explicit formatter. Which is good because as you experienced, constructing a formatter is error-prone.
In case you need a Date
object for an old API not yet upgraded to Java time, the conversion is:
Date oldfashionedDate = Date.from(dateTime.toInstant());
System.out.println(oldfashionedDate);
Output (from a device in Europe/Brussels time zone):
Tue Jul 20 21:35:20 CEST 2021
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).