设置 calendar.day_of_month 即设置 calendar.year

Seting calendar.day_of_month is setting calendar.year

我有一个最初设置为 2019-11-01 的日历,我想使用以下方法将其设置为该月的第一个日期和最后一个日期:

cal.set(int field,int value) 

对于我使用的字段:

Calendar.DATE or Calendar.DAY_OF_MONTH

但是 sysout 上的系统显示它正在设置 Calendar.YEAR 而不是

System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));

cal.set(cal.get(Calendar.DAY_OF_MONTH),1);
        
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
        
cal.set(cal.get(Calendar.DAY_OF_MONTH),cal.getActualMaximum(Calendar.DAY_OF_MONTH));

System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));

系统输出:

2019-11-01

0001-11-01

0030-11-01

你应该使用

Calendar.DAY_OF_MONTH

不是

cal.get(Calendar.DAY_OF_MONTH)

因为日历 class 有静态字段来表示每个字段的 ID,例如 DAY_OF_MONTH = 5 当您使用 cal.set(cal.get(Calendar.DAY_OF_MONTH),1) 时,您告诉日历获取等于 = 1 的 DAY_OF_MONTH 的日历值(您说cal value = 2-19-11-01), 1 是年,这样你就可以将年设置为 1 而不是日

像这样使用它: cal.set(Calendar.DAY_OF_MONTH,1);

您可以使用 java-8 现代日期时间 API LocalDate, stop using the legacy Calendar or util.Date

LocalDate date = LocalDate.parse("2019-11-01");

System.out.println(date.with(TemporalAdjusters.firstDayOfMonth()));  //2019-11-01
System.out.println(date.with(TemporalAdjusters.lastDayOfMonth()));   //2019-11-30