Java 的 Calendar 类出现意外行为
我有以下代码来获取当前系统日期的不同部分(本例为 2011 年 10 月 11 日)。
Calendar now = Calendar.getInstance();
String dt = ""+now.get(now.DATE)+"-"+now.get(now.MONTH)+"-"+now.get(now.YEAR);
在这里,DATE
和 YEAR
字段给出了预期的值,但 MONTH
字段给出了意外的结果,首先我不知道 MONTH
字段从零开始,因此当前月份为 11
将为我提供 10
。现在,如果我使用 now.get(now.MONTH+1)
,它会返回 46
。简单地使用 now.MONTH
而不是使用 get
方法会得到 2
。
那么,我在这里做错了什么?它不应该是日历类中的错误。
请注意,我使用的是 JDK 7。
I have following code to get different parts of current system Date (10-11-2011 for this case).
Calendar now = Calendar.getInstance();
String dt = ""+now.get(now.DATE)+"-"+now.get(now.MONTH)+"-"+now.get(now.YEAR);
Here, DATE
and YEAR
fields are giving values as expected but MONTH
field is giving unexpected results, firstly I didn't knew that MONTH
field starts with zero, so having current month as 11
will give me 10
. Now, if I use now.get(now.MONTH+1)
than it returns 46
. And using simply now.MONTH
instead of using get
method gives 2
.
So, what am I doing wrong here? it shouldn't be a bug in Calendar class.
Note that I'm using JDK 7.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要
now.get(Calendar.MONTH) + 1
。now.get(Calendar.MONTH)
返回从 0 开始的月份。您需要在结果中加 1。如果执行now.get(Calendar.MONTH + 1)
,您将得到除月份以外的其他内容,因为您不再将 MONTH 常量传递给 get 方法。 get 只接受一个 int 作为参数。常量 MONTH 表示“我想要获取月份”。常量 DATE 表示“我想获取日期”。它们的价值没有任何意义。 MONTH 为 2,3 为 WEEK_OF_YEAR。另请注意,应使用类名而不是类的实例来访问静态变量(或常量)。
您是否考虑过使用
SimpleDateFormat
?这是使用特定模式格式化日期的类:You need
now.get(Calendar.MONTH) + 1
.now.get(Calendar.MONTH)
returns the month starting at 0. And you need to add 1 to the result. If you donow.get(Calendar.MONTH + 1)
, you're getting something other than the month, because you don't pass the MONTH constant to the get method anymore. get just takes an int as parameter. The constant MONTH means "I want to get the month". The constant DATE means "I want to get the date". Their value has no meaning. MONTH is 2, and 3 is WEEK_OF_YEAR.Also note that static variables (or constants) should be accessed using the class name, and not an instance of the class.
Have you considered using
SimpleDateFormat
? That's the class to use to format a Date using a specific pattern:根据 Javadoc,月份是零索引的:
与
日历
类似您需要添加 1 以数字方式显示它或使用
java.text.SimpleDateFormat
它将自动为您执行此操作。如果您对日期进行了大量工作,那么我建议使用 Joda 时间。它比 Java 核心库的日期/时间处理要好得多。
Month is zero-indexed according to the Javadoc:
and similarly for
Calendar
You need to add 1 to it to display it numerically or use
java.text.SimpleDateFormat
which will do this automatically for you.If you're doing a lot of work with dates, then I suggest using Joda time instead. It is much better than the Java core library date/time handling.