在我的网络应用程序中,我将所有最终用户的日期信息以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区域内,那么我该如何改进方法以完美地适应他们的本地时钟时间。
答案 0 :(得分:4)
如果您使用自定义时区ID,例如GMT + 10,您将获得不支持DST的TimeZone,例如TimeZone.getTimeZone("GMT+10").useDaylightTime()
返回false。但是如果您使用支持的ID,例如“America / Chicago”,您将获得支持DST的TimeZone。 TimeZone.getAvailableIDs()
返回支持的完整ID列表。内部Java在jre / lib / zi中存储时区信息。