Reputation: 3063
I am trying to convert server date string to my local/device set local time but without success. I am using Joda time library.
What i am trying to do:
private static String FORMAT_DATE_SERVER = "YYYY-MM-dd'T'HH:mm:ssZ";
public static DateTime parseServerDateToLocal(String raw_date) {
DateTime result = DateTime.parse(raw_date, DateTimeFormat.forPattern(FORMAT_DATE_SERVER)).withZone(DateTimeZone.getDefault());
return result;
}
Still returns the DateTime from the server. I cant manage to make it to return the proper hour/datetime.
I read many post about this, but i didnt manage to make it simple, clean and working.
Upvotes: 2
Views: 2746
Reputation: 3063
The solution i have found:
in your application class, or somewhere else, initialise JodaTimeAndroid:
JodaTimeAndroid.init(this);
after this initialisation the date will be automatically converted to your zone, with proper offset. This is how you parse the data then:
private static String FORMAT_DATE_SERVER = "yyyy-MM-dd'T'HH:mm:ssZ";
private static String raw_date = "2015-06-18T08:52:27Z";
public static DateTime parseServerDateToLocal(String raw_date) {
return DateTime.parse(raw_date, DateTimeFormat.forPattern(FORMAT_DATE_SERVER));
}
In my case, with offset (+2h), the returned data is:
2015-06-18T10:52:27.000+02:00
Upvotes: 4
Reputation: 13348
Try this code
Example Converting a date String of the format "2011-06-23T15:11:32" to out time zone.
private String getDate(String dateString) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = null;
try {
value = formatter.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy hh:mmaa");
dateFormatter.setTimeZone(TimeZone.getDefault());
String dt = dateFormatter.format(value);
return dt;
}
Upvotes: 1