为什么Calendar.JUNE将月份设置为7月?

Kje*_*din 4 java date gregorian-calendar dst

我想你们有些人读过这个标题,并且"哦,另一个关于java的基于0的月系统的问题......".好吧,不是这次.

在我们切换到夏令时之后,我的java日历对象表现得很好.将月份设置为JUNE,实际上将其设置为7月.我不知道为什么,但有人建议我Locale在日历的构造函数参数中设置- 对象.那没用.以下代码01-07-14在我的控制台中返回.

有任何想法吗?

public class test {

    public static void main(String[] args){
        Locale locale = new Locale("da-DK");
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");

        Calendar date = new GregorianCalendar(locale);
        date.set(Calendar.MONTH, Calendar.JUNE);
        System.out.println(sdf.format(date.getTime()));
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

这也回来了 01-07-14

public class test {

    public static void main(String[] args){
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
        TimeZone timeZone = TimeZone.getTimeZone("Europe/Copenhagen");

        Calendar date = new GregorianCalendar(timeZone);
        date.set(Calendar.MONTH, Calendar.JUNE);
        System.out.println(sdf.format(date.getTime()));
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*eel 5

今天是三月三十一日.设置日历的月份时,当前日期仍然设置,但6月31日不存在,因此Calendar滚动到7月1日.

  • 打败我,'date.set(Calendar.DAY_OF_MONTH,1);`修复它;) (2认同)