The final goal is to convert a timestamp passed down from the server to local time.
Here's what I get:
2018-04-05T16:14:19.130Z
However, my local time is 11:14 AM CST
. Here's what I've tried:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
final LocalTime localTime = formatter.parseLocalTime(text);
Timber.i(localTime.toString()); // output: 16:14:19.070
Output is: 16:14:19.070
. Does anybody know how to use it? I expected to receive something like 11:14 AM
.
Also, I've tried using this:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
final DateTime time = formatter.parseDateTime(text);
Timber.i(time.toString()); // output: 2018-04-05T16:14:19.490-05:00
Looks like it's a 5-hour difference there? Does anybody know how I can use this to convert to local time?
The "Z" in the end means that the date/time is in UTC. If you put it inside quotes, it's treated as a literal (the letter "Z" itself) and it loses this special meaning - you're basically throwing away the information that it's in UTC, and DateTime
assumes the JVM default timezone (that's why your second attempt results in 16:14 in UTC-05:00).
DateTime
can parse this input directly:
String input = "2018-04-05T16:14:19.130Z";
DateTime dt = DateTime.parse(input);
Then you convert this to the desired timezone. You can do:
dt = dt.withZone(DateTimeZone.getDefault());
Which will use your JVM's default timezone. But this is not so reliable, because the default can be changed at runtime - even by other applications running in the same JVM - so it's better to use an explicit timezone:
dt = dt.withZone(DateTimeZone.forID("America/Chicago"));
Then you can convert it to the format you want:
String time = dt.toString("hh:mm a"); // 11:14 AM
If you need to use a formatter, you can remove the quotes around "Z" and also set the timezone in the formatter:
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
// zone to be used for the formatter
.withZone(DateTimeZone.forID("America/Chicago"));
DateTime dateTime = parser.parseDateTime("2018-04-05T16:14:19.130Z");
String time = dateTime.toString("hh:mm a"); // 11:14 AM