Unexpected behavior with Calendar class of Java

两盒软妹~` 提交于 2021-01-28 08:22:49

问题


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.


回答1:


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 do now.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:

new SimpleDateFormat("dd/MM/yyyy").format(now.getTime());



回答2:


Month is zero-indexed according to the Javadoc:

A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.

and similarly for Calendar

The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

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.

Joda-Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API. The 'default' calendar is the ISO8601 standard which is used by XML. The Gregorian, Julian, Buddhist, Coptic, Ethiopic and Islamic systems are also included, and we welcome further additions. Supporting classes include time zone, duration, format and parsing.



来源:https://stackoverflow.com/questions/8070826/unexpected-behavior-with-calendar-class-of-java

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