Java 如何将本地时间转换为UTC,请记住日光节约系数
在我的web应用程序中,我将所有最终用户的日期信息以UTC格式存储在数据库中,在向他们显示之前,只需将UTC日期转换为他们选择的时区 我使用此方法将localtime转换为UTC时间(同时存储): 以及将UTC日期转换为本地日期的方法(显示时):Java 如何将本地时间转换为UTC,请记住日光节约系数,java,grails,groovy,Java,Grails,Groovy,在我的web应用程序中,我将所有最终用户的日期信息以UTC格式存储在数据库中,在向他们显示之前,只需将UTC日期转换为他们选择的时区 我使用此方法将localtime转换为UTC时间(同时存储): 以及将UTC日期转换为本地日期的方法(显示时): 我的问题是,如果最终用户在DST区域内,那么我如何改进方法以完美地适应他们的本地时钟时间。如果使用自定义时区ID,如GMT+10,您将得到不支持DST的时区,例如TimeZone.getTimeZone(“GMT+10”)。useDaylightTim
我的问题是,如果最终用户在DST区域内,那么我如何改进方法以完美地适应他们的本地时钟时间。如果使用自定义时区ID,如GMT+10,您将得到不支持DST的时区,例如
TimeZone.getTimeZone(“GMT+10”)。useDaylightTime()
返回false。但如果您使用支持的ID,例如“America/Chicago”,您将获得支持DST的时区。受支持ID的完整列表由TimeZone.getAvailableIDs()
返回。Java在内部将时区信息存储在jre/lib/zi中。这是否意味着如果我使用America/Chicago
之类的时区ID,而这些ID存在于timezone.getAvailableIDs()
列表中,我就不必担心DST了?或者,我仍然需要检查timezone.inDaylightTime(date)
并增加/减少与时区的偏移量。getDSTSaviews()
?@tusar如果您获得了美国/芝加哥的时区,并将其设置为Calendar/SimpleDateFormat,则Calendar/SimpleDateFormat将在记住DST的情况下起作用。
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()
}
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())
}