开发者

Java GregorianCalendar What am I doing wrong? Wrong date?

Hello I have a problem with GregorianCalendar.

What is wrong in there?

How outcome is 2010/6/1 and not 2010/05/31?

package test;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Main {

    public static void main(String[] args) {
        Calendar cal = new GregorianCalendar(2010, 5, 31);
        System.out.println开发者_StackOverflow社区(cal.get(Calendar.YEAR) + "/" + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.DAY_OF_MONTH));
    }

}


Java counts months from 0, so 5 is June. It's always safer to use the constants. So I would write:

Calendar cal = new GregorianCalendar(2010, Calendar.MAY, 31);

The same applies to your calendar print out. If you do cal.get(Calendar.MONTH) you get 6 meaning JULY.


This is because month number is zero-based, so you are trying to set 31st of June, but June is only 30 days, so it gets converted to 1st of July.


Toadd to what the above answers, since there is no 31st day in June the Calendar promotes it to the next valid day because Calendar.setLenient is true by default.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜