2014-09-22 42 views
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"))); 

dt中的时间是UTC,我想将时间设置为dt加上毫秒到GMT?但是,时间仍然以UTC格式打印(格林威治标准时间后1小时)。我如何设置它,因此它在前面一个小时?在乔达将UTC转换为LocalDateTime?

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

我知道时间是整整一个小时的背后,因为我提出这个要求在15点44分16秒GMT

+0

你是什么意思“dt中的时间是UTC”?显然,第一行输出并不是这种情况。你的意思是'“2014-09-15T21:20:14”'意思是UTC? – 2014-09-22 15:01:34

+0

是的,抱歉,如果它不清楚乔恩。 – Adz 2014-09-22 15:02:17

回答

4

DateTime实际上是在UTC - 这是系统默认的时区。为了解决这个问题,你只需要告诉它你传递的价值是在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); 

输出:

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

另外请注意,你不能取得在请求格林威治标准时间15:44:16,因为这还没有发生。在我写这篇文章的时候,这是英国夏令时16:05,因此格林威治标准时间15:05。了解英国的时区不是“GMT”时非常重要 - 这只是我们不遵守夏令时的时区的一部分。

如果要转换到英国时区,你想:

DateTime other = dt.plusMillis(581042272) 
    .withZone(DateTimeZone.forID("Europe/London")); 
+0

完美的乔恩,谢谢。 – Adz 2014-09-22 15:18:24

0
val marketCentreTime = timeInAnotherTimezone.withZone(DateTimeZone.forID("yourCountryName/andyourCityName")); 
5

对于那些有麻烦从服务器转换日期时间当地日期时间:

词根记忆确定服务器给你一个UTC时间,也就是说,格式应该包含一个时区。 2.使用模式转换,如果api不给你一个时区,那么你可能会因为最后的'Z'而得到一个异常。

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
     DateTime dt = formatter.parseDateTime(currentPost.postDate); 

3.to检查(时间偏移量(可选)

DateTimeZone ActualZone = dt.getZone(); 

4.Convert本地时间

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

如果你自己控制API,它恰巧是一个asp.net API,check this,设置日期时间的Kind,即使您可能已将其作为UTC时间保存在数据库中,也会将日期时间与默认值一起发送服务器时区)