3
        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")));

the time in dt is in UTC, I want to set the time in dt plus milliseconds to GMT? However, the time is still printed as UTC (1 hour behind GMT). How can I set it so it's one hour in front?

2014-09-15T21:20:14.000+01:00
2014-09-22T14:44:16.272Z

I know the time is exactly one hour behind because I made this request at 15:44:16 GMT

Adz
  • 2,809
  • 10
  • 43
  • 61
  • What do you mean by "the time in dt is in UTC"? That's clearly not the case given your first line of output. Do you mean `"2014-09-15T21:20:14"` is meant to be UTC? – Jon Skeet Sep 22 '14 at 15:01
  • Yes, sorry if it wasn't clear Jon. – Adz Sep 22 '14 at 15:02

3 Answers3

7

Your DateTime is actually not in UTC - it's in the system default time zone. To fix it, you just need to tell it that the value you're passing in 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 can't have made the request at 15:44:16 GMT, as that hasn't occurred yet. At the time I'm writing this, it's 16:05 British Summer Time, therefore 15:05 GMT. It's important to understand that the time zone in the UK isn't "GMT" - that's just the part of the time zone when we're not observing daylight savings.

If you want to convert to the UK time zone, you want:

DateTime other = dt.plusMillis(581042272)
    .withZone(DateTimeZone.forID("Europe/London"));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

For those that have trouble with converting datetime from a server to local datetime:

1.Make sure the server gives you a UTC time, meaning, the format should contain a timezone. 2.Convert with pattern, if the api does not give you an timezone, then you might get an exception because of the 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.Convert to local time

TimeZone tz2 = TimeZone.getDefault();
        DateTime localdt = new DateTime(dt, DateTimeZone.forID(tz2.getID()));

(if you control the API yourself, and it happens to be an asp.net api, check this, to set the Kind of the datetime, even though you might have saved it as UTC time in the database, you will send the datetime with the default server timezone)

Community
  • 1
  • 1
CularBytes
  • 9,924
  • 8
  • 76
  • 101
0
val marketCentreTime = timeInAnotherTimezone.withZone(DateTimeZone.forID("yourCountryName/andyourCityName"));
Ferrakkem Bhuiyan
  • 2,741
  • 2
  • 22
  • 38