简体   繁体   English

Java Calendar加或减小时时的奇怪行为

[英]Java Calendar strange behaviour when add or subtract hours

When I add or subtract hours it seems the Calendar object has some unexpected behaviour (at least I think so) 当我增加或减少小时数时,Calendar对象似乎有一些意外行为(至少我这样认为)

Can someone explain this, I first add 2 hours after that I subtract 3 hours, so my time should be 1 less then were i started at. 有人可以解释一下,我先加2个小时,再减去3个小时,所以我的时间应该比我开始时少1个小时。 What am I thinking wrong here?: 我在想什么错呢?:

    Calendar calReference= new GregorianCalendar(2014,9,26);    
    sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    System.out.println("test dummy "+sdf.format(calReference.getTime()));
    calReference.add(Calendar.HOUR_OF_DAY, 2);
    //calReference.set(Calendar.MINUTE, 0);
    System.out.println("test dummy "+sdf.format(calReference.getTime()));
    calReference.add(Calendar.HOUR_OF_DAY, -3);
    //calReference.set(Calendar.MINUTE, 0);
    System.out.println("test dummy "+sdf.format(calReference.getTime()));

I got output I never expected myself: 我得到了我从未期望过的输出:

test dummy 2014/10/26 00:00:00 测试假人2014/10/26 00:00:00

test dummy 2014/10/26 02:00:00 测试假人2014/10/26 02:00:00

test dummy 2014/10/26 00:00:00 => this should be 2014/10/25 23:00:00. 测试假人2014/10/26 00:00:00 =>这应该是2014/10/25 23:00:00。

or am I missing something here myself. 还是我自己在这里错过了什么。

Try adding your desired locale into the SimpleDateFormat: 尝试将所需的语言环境添加到SimpleDateFormat中:

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

The Java documentation for Locale.getDefault() states: 用于Locale.getDefault()的Java文档指出:

The Java Virtual Machine sets the default locale during startup based on the host environment. Java虚拟机将在启动期间根据主机环境设置默认语言环境。 It is used by many locale-sensitive methods if no locale is explicitly specified. 如果未明确指定语言环境,则许多语言环境敏感方法都会使用它。 It can be changed using the setDefault(Locale.Category, Locale) method. 可以使用setDefault(Locale.Category,Locale)方法更改它。

So the default locale in your JVM may be incorrect. 因此,JVM中的默认语言环境可能不正确。

This post delves a little deeper into how the default locale for your application is determined. 这篇文章深入探讨了如何确定应用程序的默认语言环境。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM