Convert UTC to LocalDateTime in Joda?
DateTime dt = new DateTime("2014-09-15T21:20:14");
System.out.println(dt);
System.out.println(dt.plusMillis(581042272).toDateTime().toLocalDateTime().toDateTime(DateTimeZone.forID("GMT")));
time in dt in UTC, I want to set time in dt plus milliseconds to GMT? However, the time is still printed as UTC (1 hour behind GMT). How can I set it like this one hour ahead?
2014-09-15T21:20:14.000+01:00
2014-09-22T14:44:16.272Z
I know the time is one hour less because I made this request at 15:44:16 GMT
source to share
Yours DateTime
isn't actually in UTC - it's in the system's default timezone. To fix this, you just need to say that the value you are passing is in UTC:
DateTime dt = new DateTime("2014-09-15T21:20:14", DateTimeZone.UTC);
System.out.println(dt);
DateTime other = dt.plusMillis(581042272);
System.out.println(other);
Output:
2014-09-15T21:20:14.000Z
2014-09-22T14:44:16.272Z
Also note that you could not make your request at 15:44:16 GMT as that has not happened yet. At the time I write this, it is 16:05 British Summer Time, so it is 15:05 GMT. It is important to understand that the UK time zone is not "GMT" - it is only part of the time zone when we are not observing Daylight Saving Time.
If you want to convert to UK timezone, you want:
DateTime other = dt.plusMillis(581042272)
.withZone(DateTimeZone.forID("Europe/London"));
source to share
For those having trouble converting datetime from server to local datetime:
1. Make sure the server gives UTC time, that is, the format must contain the time zone. 2.Convert with template, if api doesn't give you timezone then you might get an exception due to last "Z".
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
DateTime dt = formatter.parseDateTime(currentPost.postDate);
3. To check the time offset (optional)
DateTimeZone ActualZone = dt.getZone();
4. Go to local time
TimeZone tz2 = TimeZone.getDefault();
DateTime localdt = new DateTime(dt, DateTimeZone.forID(tz2.getID()));
(if you are in control of the API itself and that means the api, check this to set Kind
to datetime although you could store it as UTC time in the database, you will send the datetime with the default server timezone)
source to share