2014-03-29 21 views
1

我想將我的當前時區的日期轉換爲UTC。從當前的TimeZone轉換爲UTC遞減2小時而不是1

結果對我來說是不可理解的。

代碼:

public static String convertToUTC(String dateStr) throws ParseException 
{ 

    Log.i("myDateFunctions", "the input param is:"+dateStr); 

    String uTCDateStr; 


    Date pickedDate = stringToDate(dateStr, "yyyy-MM-dd HH:mm:ss"); 

    Log.i("myDateFunctions", "the input param after it is converted to Date:"+pickedDate); 


    TimeZone tz = TimeZone.getDefault(); 
    Date now = new Date(); 
    Log.i("myDateFunctions:", "my current Timezone:"+tz.getDisplayName()+" +"+(tz.getOffset(now.getTime())/3600000)); 

    // Convert to UTC 
    SimpleDateFormat converter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    converter.setTimeZone(TimeZone.getTimeZone("UTC")); 
    uTCDateStr = converter.format(pickedDate); 

    Log.i("myDateFunctions", "the output, after i converted to UTC timezone:"+uTCDateStr); 

    return uTCDateStr; 

} 

而且logcat的結果是:

03-29 20:31:46.804: I/myDateFunctions(18413): the input param is:2014-04-29 20:00:00 
03-29 20:31:47.005: I/myDateFunctions(18413): the input param after it is converted to Date:Tue Apr 29 20:00:00 CEST 2014 
03-29 20:31:47.005: I/myDateFunctions:(18413): my current Timezone:Central European Time +1 
03-29 20:31:47.005: I/myDateFunctions(18413): the output, after i converted to UTC timezone:2014-04-29 18:00:00 

正如你可以看到: 我的時區爲CET (GMT + 1)

那麼,爲什麼,如果我的輸入是20:00我回到18:00而不是19:00?

+0

您的時區是否有夏令時?如果是這樣,那可能會增加1小時到轉換(UTC不)。 –

+0

我總是wan why爲什麼ppl在stackoverflw害怕給出答案。也許是因爲downvotes?那麼,你是對的。請將此作爲答案寫下,以便我可以接受。 –

+0

我在猜測時使用了一條評論,因此查看列表的人不會認爲它已被回答。 –

回答

2

問題是夏時制。 UTC沒有它,如果你的這一部分時間會增加1小時的差異。

0

answer by Game Sechan看起來是正確的。

我只是想表明,使用Joda-Time或java.time而不是使用出色的java.util.Date和.Calendar類時,這項工作更容易。

喬達時間

Joda-Time 2.4。

String inputRaw = "2014-04-29 20:00:00"; 
String input = inputRaw.replace(" ", "T"); 
DateTimeZone timeZoneIntendedByString = DateTimeZone.forID("America/Montreal"); // Or DateTimeZone.getDefault(); 
DateTime dateTime = new DateTime(input, timeZoneIntendedByString); 
DateTime dateTimeUtc = dateTime.withZone(DateTimeZone.UTC); // Adjust time zones, but still same moment in history of the Universe. 
相關問題