Java Calendar strange behaviour when add or subtract hours

大憨熊 提交于 2019-12-11 16:45:58

问题


When I add or subtract hours it seems the Calendar object has some unexpected behaviour (at least I think so)

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. 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

test dummy 2014/10/26 02:00:00

test dummy 2014/10/26 00:00:00 => this should be 2014/10/25 23:00:00.

or am I missing something here myself.


回答1:


Try adding your desired locale into the SimpleDateFormat:

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

The Java documentation for Locale.getDefault() states:

The Java Virtual Machine sets the default locale during startup based on the host environment. 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.

So the default locale in your JVM may be incorrect.

This post delves a little deeper into how the default locale for your application is determined.



来源:https://stackoverflow.com/questions/26979191/java-calendar-strange-behaviour-when-add-or-subtract-hours

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!