Reputation: 4897
I want to use Joda Time library in android to convert time to phone local timezone.
I have the time that is in UTC for example: 2016-01-14 11:13:56
My current Time is: 2016-01-14 12:13:56
When I run this code:
DateTime dt = new DateTime(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime(usersResponse.lastUpdate),
DateTimeZone.UTC);
String time = String.valueOf(dt));
I get: 2016-01-14T10:13:56.000Z
When I run this code:
DateTime dt = DateTime.parse(usersResponse.lastUpdate, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
String time = String.valueOf(dt));
I get: 2016-01-14T11:13:56.000+01:00
When I run this code:
DateTime dt = new DateTime(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime(usersResponse.lastUpdate),
DateTimeZone.forID("Europe/Rome"));
String time = String.valueOf(dt));
I get: 2016-01-14T11:13:56.000+01:00
But this is wrong I should have received: 2016-01-14T12:13:56.000+02:00
Is there any configuration that I am missing. Is this problem related with daylight saving time(from some question here in SO I have seen that Joda Time manages that)
How can I manage to get the time in device local time.
Thanks
Upvotes: 2
Views: 2049
Reputation: 1666
A DateTime object represents a particular millisecond since the unix epoch. This is a canonical representation of the moment of time that you are trying to represent.
A print out of that DateTime object according to what you would call that millisecond if you are in Rome or London or New York is like a String alias for a particular millisecond.
When you do:
String time = String.valueOf(dt));
You are just saying "give me a String representation of the milleseconds that back the DateTime object, you are not specifiying which TimeZone alias you want for that millisecond, and so it gives it to you in UTC.
This:
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime(usersResponse.lastUpdate)
is not specifying which timezone you want the formatter to use, so it will assume UTC. All your usages of creating DateTime objects after that is irrelevent, the milliseconds are set.
Rather do this:
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(Time_you_are_coming_from);
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(time_your_are_converting_to);
dt = inputFormatter.parseDateTime("2016-01-14 11:13:56");
System.out.println(outputFormatter.print(dt));
Upvotes: 5