Java Calendar加或减小时时的奇怪行为 [英] Java Calendar strange behaviour when add or subtract hours

查看:130
本文介绍了Java Calendar加或减小时时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我增加或减少小时数时,似乎Calendar对象有一些意外行为(至少我认为是这样)

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

有人可以解释一下,我先加2小时之后,我减去3个小时,因此我的时间应该比开始时少1个小时。我在想什么错了?

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:

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

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

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

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

test dummy 2014/10/26 00:00:00 =>这应该是2014/10/25 23: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.

推荐答案

尝试添加您所需的语言环境进入SimpleDateFormat:

Try adding your desired locale into the SimpleDateFormat:

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

Locale.getDefault()的Java文档指出:

The Java documentation for Locale.getDefault() states:


Java虚拟机将在启动期间根据主机环境设置默认语言环境。如果未明确指定语言环境,则许多语言环境敏感方法都会使用它。可以使用setDefault(Locale.Category,Locale)方法进行更改。

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.

因此,JVM中的默认语言环境可能不正确。

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.

这篇关于Java Calendar加或减小时时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆