2012-12-19 78 views
3

在我的Web應用程序中,我將所有最終用戶的日期信息作爲UTC格式存儲在數據庫中,並在向他們顯示之前將UTC日期轉換爲時區他們的選擇。如何將本地時間轉換爲UTC記住DayLightSaving因子

我使用這種方法來轉換本地時間到UTC時間(同時存儲):

public static Date getUTCDateFromStringAndTimezone(String inputDate, TimeZone timezone){ 
    Date date 
    date = new Date(inputDate) 

    print("input local date ---> " + date); 

    //Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT 
    long msFromEpochGmt = date.getTime() 

    //gives you the current offset in ms from GMT at the current date 
    int offsetFromUTC = timezone.getOffset(msFromEpochGmt)*(-1) //this (-1) forces addition or subtraction whatever is reqd to make UTC 
    print("offsetFromUTC ---> " + offsetFromUTC) 

    //create a new calendar in GMT timezone, set to this date and add the offset 
    Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")) 
    gmtCal.setTime(date) 
    gmtCal.add(Calendar.MILLISECOND, offsetFromUTC) 

    return gmtCal.getTime() 
} 

而且這種方法對於UTC日期轉換爲本地(同時顯示):

public static String getLocalDateFromUTCDateAndTimezone(Date utcDate, TimeZone timezone, DateFormat formatter) { 
    printf ("input utc date ---> " + utcDate) 

    //Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT 
    long msFromEpochGmt = utcDate.getTime() 

    //gives you the current offset in ms from GMT at the current date 
    int offsetFromUTC = timezone.getOffset(msFromEpochGmt) 
    print("offsetFromUTC ---> " + offsetFromUTC) 

    //create a new calendar in GMT timezone, set to this date and add the offset 
    Calendar localCal = Calendar.getInstance(timezone) 
    localCal.setTime(utcDate) 
    localCal.add(Calendar.MILLISECOND, offsetFromUTC) 

    return formatter.format(localCal.getTime()) 
} 

我問題是,如果最終用戶在DST區域內,那麼我該如何改進方法以完美地適應當地時鐘時間。

回答

4

如果您使用自定義時區ID,例如GMT + 10,則會得到不支持DST的TimeZone,例如TimeZone.getTimeZone("GMT+10").useDaylightTime()會返回false。但是如果您使用受支持的ID,例如「America/Chicago」,您將獲得支持DST的TimeZone。支持ID的完整列表由TimeZone.getAvailableIDs()返回。 Java內部將時區信息存儲在jre/lib/zi中。

+0

這是否意味着我不需要擔心夏令時,如果我把'TimeZone.getAvailableIDs()'列表中存在的'America/Chicago'這樣的timezone id? – tusar

+0

或者,我仍然需要檢查'timezone.inDaylightTime(date)'並增加/減少'timezone.getDSTSavings()'的偏移量? – tusar

+1

@tusar如果您獲得美國/芝加哥TimeZone並將其設置爲Calendar/SimpleDateFormat,則Calendar/SimpleDateFormat將記住DST。 –

相關問題