为什么日历使用正确的时区返回错误的小时?

Ian*_*ell 8 java timezone datetime calendar


返回的时间和日期是正确的,除了小时,它比它应该小1小时.

我似乎设置了获得正确时间和日期所需的一切:

 - I'm using Calendar.getInstance(), instead of new Date()
 - I'm setting the timezone of the Calendar instance with Timezone.getTimeZone
 - I'm using DateFormat and SimpleDateFormat to format the output
Run Code Online (Sandbox Code Playgroud)


我的时区是Eastern Standard Time,又名UTC/GMT-5:00.这些行都没有任何影响:

 - cal.setTimeZone(TimeZone.getTimeZone(cal.getTimeZone().getDisplayName()));
 - cal.setTimeZone(TimeZone.getTimeZone("EST"));
 - cal.setTimeZone(TimeZone.getTimeZone("UTC"));
 - cal.setTimeZone(TimeZone.getTimeZone("GMT"));
 - cal.setTimeZone(TimeZone.getTimeZone("GMT-5:00"));
Run Code Online (Sandbox Code Playgroud)

...但是这些选项中的每一个都设定了我想要的时区.


这是我的尝试,我错误地向Calendar实例添加了1小时:

PrintWriter output = null;

try {
  output = new PrintWriter(
   new BufferedWriter(new FileWriter("output.txt", true)));

  DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:ms MM/dd/yyyy");
  Calendar cal = Calendar.getInstance();

  // ...doesn't seem to be working:
  cal.setTimeZone(TimeZone.getTimeZone(cal.getTimeZone().getDisplayName()));

  /*
   * adding an extra hour here, to make up for the incorrect hour value???
   * ...without this line, everything is correct except the hour = n - 1:
   */
  //cal.setTimeInMillis(cal.getTimeInMillis() + (1000 * 60 * 60));

  // printing to console here:
  System.out.println(dateFormat.format(cal.getTime()));
  System.out.println(cal.getTimeZone().getDisplayName());

  // printing to the log-file here:
  output.println(dateFormat.format(cal.getTime()));
  output.println(cal.getTimeZone().getDisplayName());

} catch (IOException e) {
  e.printStackTrace();

} finally {
  if (output != null) {
    output.close();
  }
}
Run Code Online (Sandbox Code Playgroud)


输出:

10:05:43:543 10/10/2013
GMT-05:00
Run Code Online (Sandbox Code Playgroud)

- 这应该是11:05:43:543!( ps - 我很遗憾不能使用Joda-Time)

Ale*_*ien 3

1)在SimpleDateFormat中设置时区

2) 使用 UTC 或“真实”时区,例如(“奥地利/维也纳”);
(国家名称和时区中最大的城市查一下即可确定)
EST(=UTC-5)不是一个非常适合计算目的的时区,因为它是没有夏令时的时间。

中欧的另一个例子:
冬季我们使用 MEZ (CET),夏季(夏令时)我们使用 (MESZ = CEST)。
但你希望你的计算机为你计算它,所以不要使用它:

时区是地缘政治因素,因此需要国家名称。
每个国家都可以决定在需要时更改其时区(例如俄罗斯前段时间,西班牙现在正在讨论。)