3

在我的 Web 应用程序中,我将所有最终用户的日期信息以 UTC 格式存储在数据库中,在向他们展示之前,只需将 UTC 日期转换为他们选择的时区。

我正在使用此方法将本地时间转换为 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

1 回答 1

4

如果您使用自定义时区 ID,例如 GMT+10,您将获得不支持 DST 的 TimeZone,例如TimeZone.getTimeZone("GMT+10").useDaylightTime()返回 false。但是,如果您使用受支持的 ID,例如“America/Chicago”,您将获得一个支持 DST 的 TimeZone。支持的 ID 的完整列表由 返回TimeZone.getAvailableIDs()。Java 在内部将时区信息存储在 jre/lib/zi 中。

于 2012-12-19T09:17:38.177 回答