I have a requirement in which I need to render localised datetime on a text view in an Android layout. The date time is returned in an ISO format from a service call. Here is the response JSON
{
"expiredTime": "2020-01-24T00:59:59.000-05:00",
. . . Other Keys and Values . . .
}
This is to be rendered in an Android app inside a text view. What I want to do is show the localised time on the app. So If the user were to view in the screen in say New York, the expired time would show 2020-01-24T00:59:59.000-05:00
because the time in the payload belongs to the same time zone as NY. Similarly, if I wanted to display in GMT, the time would be shown as 2020-01-24T05:59:59.000-00:00
.
How can I implement this correctly in Android? I have done this as shown below. The returned date is passed to a SimpleDateFormat
instance to return a string.
public static final Date parse(String dateTimeAsString) throws ParseException
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME.withLocale(Locale.getDefault()));
try
{
LocalDate localDate = LocalDate.parse(value, formatter);
if (localDate != null)
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
} catch (DateTimeParseException dtpe)
{
// If the format is invalid, then delegate to the other helper function.
}
}
return null;
}
My questions are as follows:
- Is my implementation to get the localised date correct? If not, how would I do it correctly?
- How do I localise the date for Android OS version below Oreo? DateTimeFormatter is only available in Android Oreo and up.