本文介绍了为什么日历以正确的时区返回错误的小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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



我似乎正在设置所需的一切以获取正确的时间和日期:


The time and date returned are correct except for the hour, which is 1 hour less than what it should be.

I seem to be setting everything that is required to get the correct time and date:

 c>实例添加1小时:

...but each of these options sets my desired timezone.


Here is my attempt, where I am erroneously adding 1 hour to the Calendar instance:

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();
  }
}



输出: / p>


Output:

10:05:43:543 10/10/2013
GMT-05:00

错误 - 应该是 11:05:43:543 ps - 我不幸的是不能使用 )

WRONG -- It's supposed to be 11:05:43:543! (p.s. -- I unfortunately can't use Joda-Time)

推荐答案

1)在SimpleDateFormat中设置TimeZone

1) Set the TimeZone in SimpleDateFormat

2)使用UTC或真实时区(奥地利/维也纳);

(国家名称,TimeZone中最大的城市,可以肯定的是)

EST(= UTC-5)不是非常适合计算目的的时区,因为它是没有夏令时的时间。

2) Either use UTC, or a "real" Time Zone like ("Austria/Vienna");
(Country name, and biggest city in TimeZone look it up to be sure)
EST (=UTC-5) is not a time zone very suitable for computational purpose, because it is the time without daylight saving.

另一个中欧欧洲的例子:

在冬天,我们使用MEZ(CET),夏天(夏令时)我们使用(MESZ = CEST )

但是您希望您的计算机为您排队,因此请勿使用:

One more example from central europe:
In Winter we use MEZ (CET), in Summer (Daylight savings) we use (MESZ = CEST).
But you want that your computer caluclates that for you, so don't use that:

TimeZones具有地道条件,因此名称这个国家是需要的。

每个国家都可以决定改变时区(例如俄罗斯前一段时间,西班牙现在正在讨论)。

TimeZones are geo poilitical, therfore the name of the country is needed.
Each country can decide to change its time zone when they want (e.g russia some time ago, and spain is discussing now.)

这篇关于为什么日历以正确的时区返回错误的小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 16:02