简体   繁体   English

设置 calendar.day_of_month 就是设置 calendar.year

[英]Seting calendar.day_of_month is setting calendar.year

I have a calendar initially set to 2019-11-01, that i want to set to the first date and the last date of month using the:我有一个最初设置为 2019-11-01 的日历,我想使用以下方法设置为每月的第一个日期和最后一个日期:

cal.set(int field,int value) 

And for the field i use either:对于我使用的领域:

Calendar.DATE or Calendar.DAY_OF_MONTH

But system on sysout shows that it is setting the Calendar.YEAR instead但是 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()));

Sysout:系统输出:

2019-11-01 2019-11-01

0001-11-01 0001-11-01

0030-11-01 0030-11-01

You can use the java-8 modern date time API LocalDate , stop using the legacy Calendar or util.Date您可以使用 java-8 现代日期时间 API LocalDate ,停止使用旧版Calendarutil.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

you should use你应该使用

Calendar.DAY_OF_MONTH日历.DAY_OF_MONTH

NOT不是

cal.get(Calendar.DAY_OF_MONTH) cal.get(日历.DAY_OF_MONTH)

since the Calendar class have static fields to represents the ID of each field, for example DAY_OF_MONTH = 5 and when you use cal.set(cal.get(Calendar.DAY_OF_MONTH),1) you told the calendar to get the calendar value of DAY_OF_MONTH which is equal to = 1 (you said the cal value = 2-19-11-01), and 1 is the Year, so that you get the year set to 1 instead of the day因为日历 class 有 static 字段来表示每个字段的 ID,例如 DAY_OF_MONTH = 5 并且当您使用 cal.set(cal.get(Calendar.DAY_OF_MONTH),1) 时,您告诉日历获取 DAY_OF_ 的日历值等于 = 1(你说 cal 值 = 2-19-11-01),1 是年份,因此你将年份设置为 1 而不是天

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM