Java ,将分钟添加到 Date ,奇怪的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/285818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:33:24  来源:igfitidea点击:

Java , adding minutes to a Date , weird anomaly

javadate

提问by user27262

With Java Version 1.5.0_06 on both Windows and Ubuntu Linux :

在 Windows 和 Ubuntu Linux 上使用 Java 版本 1.5.0_06:

Whenever I add minutes to the date "2008/10/05 00:00:00" , it seems that an extra hour is wrongly added.

每当我在日期 "2008/10/05 00:00:00" 上添加分钟时,似乎错误地添加了一个额外的小时。

ie: adding 360 minutes to 2008/10/05 00:00:00 at midnight should arrive at 2008/10/05 06:00:00

即:将 360 分钟添加到 2008/10/05 00:00:00 午夜应到达 2008/10/05 06:00:00

But it is arriving at 2008/10/05 07:00:00

但它是在 2008/10/05 07:00:00 到达的

The totally perplexing thing is that this ONLYhappens when the day is 2008/10/05, all other days that I try perform the minutes addition correctly.

在完全令人费解的是,这只有当这一天是2008年10月5日发生的,所有其他的日子,我尝试正确执行分钟,然后加入。

Am I going crazy or is this a bug in Java ?

我疯了还是这是 Java 中的错误?

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    try {
        String date = "2008/10/05 00:00:00";
        int minutesToAdd = 360;  // 6 hrs

        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(date));
        cal.add(Calendar.MINUTE, minutesToAdd);
        System.out.println(cal.getTime());

    } catch (ParseException e) {}

回答by Chris Jester-Young

There's a crossover to daylight savings on that day.

那天与夏令时有交叉。

Are you in New Zealand? If so, that means your timezone files are out of date. Better go to the Java download site and download new ones; look for "JDK DST Timezone Update Tool".

你在新西兰吗?如果是这样,则意味着您的时区文件已过期。最好去Java下载站点下载新的;寻找“JDK DST 时区更新工具”。

回答by toolkit

Could this be daylight savings kicking in?

这可能是夏令时开始吗?

回答by Willi aus Rohr

Take a look at Joda-Time.

看看Joda-Time

From the Documentation:

从文档:

"Joda-Time has been created to radically change date and time handling in Java. The JDK classes Date and Calendar are very badly designed, have had numerous bugs and have odd performance effects."

“Joda-Time 的创建是为了从根本上改变 Java 中的日期和时间处理。JDK 类 Date 和 Calendar 的设计非常糟糕,有很多错误,并且有奇怪的性能影响。”