java - SimpleDateFormat 行为不一致

标签 java simpledateformat

请看下面的一段代码:

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 个原因:

  1. 为什么我传递了 +0300 TZ 而默认情况下我收到了 +0200? (SimpleDateFormat 应该总是使用 TimeZone.getDefault 除非 另有说明)。
  2. 为什么仅仅因为我在它的日历实例上调用了 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, the computeFields() method is called to calculate all calendar field values.

我查了源here ,但代码对于最新的 Java 版本也是相同的。

关于java - SimpleDateFormat 行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31205846/

相关文章:

java - 如何在 2D 平面上随机生成一堆站点,它们之间的空间量大致相同?

java - 使用 NLTK 使用 MaltParser 解析多个句子

java - 将日期格式从 php 转换为 Java?

java - 从 TextView 获取 Unix 时间

java - 如何控制 SimpleDateFormat 解析为 19xx 或 20xx?

java - 无法解析日期并获取毫秒

java - java.text.SimpleDateFormat 中的奇怪行为期望 yyyyMMdd 给定 yyyy-MM-dd

java - Spring Data 存储库是如何实际实现的?

java - 访问EntityManager时出现NullPointerException

我不知道的Java语法