2012-12-19 63 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。 –

相关问题