问题
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