请看下面的一段代码:
String timeString = "1980-01-01T14:00:00+0300";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date2 = sdf.parse(timeString);
// sdf.getCalendar().get(Calendar.ZONE_OFFSET);
System.out.println(sdf.format(date2));
现在,我所在的国家/地区有 +2h
偏移量,+1
夏令时(目前)。
如果我按原样运行这段代码,它将打印
1980-01-01T13:00:00+0200
如果我取消注释询问日历偏移量的行,程序的输出是
1980-01-01T14:00:00+0300
知道为什么会这样吗?我怎样才能获得一致的输出?
为了避免更多不清楚的事情: 由于我正在处理一些遗留代码,Java 8 不是一个选项。是的,这里的关键点是为什么,而不是解决方法是什么? 并且有 2 个原因:
- 为什么我传递了 +0300 TZ 而默认情况下我收到了 +0200? (SimpleDateFormat 应该总是使用 TimeZone.getDefault 除非 另有说明)。
- 为什么仅仅因为我在它的日历实例上调用了 getter 就给出了不同的答案。
最佳答案
问题是,Calendar#get
不是一个简单的 getter,它看起来像这样:
public int get(int field)
{
complete();
return internalGet(field);
}
根据 Javadoc,complete
执行此操作的地方:
Fills in any unset fields in the calendar fields. First, the
computeTime()
method is called if the time value (millisecond offset from the Epoch) has not been calculated from calendar field values. Then, thecomputeFields()
method is called to calculate all calendar field values.
我查了源here ,但代码对于最新的 Java 版本也是相同的。
关于java - SimpleDateFormat 行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31205846/