TimeZone偏移显示无效值

时间:2016-09-29 07:19:17

标签: java date timezone

除非我做错了...

我住在波兰(GMT + 2)。当我写这篇文章时,我们处于夏令时。但是,以下代码表示GMT时间偏移仅为1小时而不是2小时。

  Calendar mCalendar = new GregorianCalendar();
  TimeZone mTimeZone = mCalendar.getTimeZone();
  System.out.println(mTimeZone);
  int mGMTOffset = mTimeZone.getRawOffset();
  System.out.printf("GMT offset is %s hours", TimeUnit.HOURS.convert(mGMTOffset, TimeUnit.MILLISECONDS));

打印GMT偏移量为1小时

其他时区也是如此,例如纽约,即GMT-4:

Calendar mCalendar = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));

打印GMT偏移量为-5小时

2 个答案:

答案 0 :(得分:2)

您必须使用TimeZone的两种方法:

您可以使用以下命令检查日期是否在DaylightSaveTime中:

mTimeZone.inDaylightTime(date)

如果这是真的,你必须添加

的值
mTimeZone.getDSTSavings()

到偏移量:

Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
System.out.println("TimeZone: "+mTimeZone);
int mGMTOffset = mTimeZone.getRawOffset();
if (mTimeZone.inDaylightTime(mCalendar.getTime())){
    mGMTOffset += mTimeZone.getDSTSavings();
}
System.out.printf("GMT offset is %s hours", 
TimeUnit.HOURS.convert(mGMTOffset, TimeUnit.MILLISECONDS));

输出:

GMT offset is 2 hours

答案 1 :(得分:1)

检查DST是否在java中处于活动状态。

TimeZone tz = TimeZone.getTimeZone("America/New_York");
boolean inDs = tz.inDaylightTime(new Date());

下面的代码为您提供DST时间

TimeZone zone = TimeZone.getTimeZone("America/New_York");
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(zone);

System.out.println(format.format(new Date()));