Is this a date in February or in March? cal.set(2010, 1, 10)
I have set this calendar in my app:
Calendar cal = Calendar.getInstance();
cal.set(2010, 1, 10);
I'm using this SimpleDateFormat
to get the month as a word:
SimpleDateFormat formatMonth = new SimpleDateFormat("MM");
In one 开发者_JAVA百科class it comes out as February
10th, 2010
.
In another it comes out as March
10th, 2010
.
Which is correct?
The month
argument to Calendar.set() is zero-based, so 1
means February
. The first behavior is the correct one.
I suspect something in your other class is mistakenly trying to compensate for zero-based month indexes, and that results in an off-by-one error.
The calendar class has constants for months
Calendar.JANUARY
for example. You should be using those.
Given all the hassles associated with the JDK date handling, you should really be looking to use Joda time instead. The above code would be rewritten as
DateTime dt = new DateTime().withDate(2010,2,10).withTime(12,13,14,0);
and represents 10 February 2010 at 12:13:14.000 in UTC. No ambiguity, thread safe and immutable.
You should note that SimpleDateFormat is not thread safe.
精彩评论