简体   繁体   中英

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:

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

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

0001-11-01

0030-11-01

You can use the java-8 modern date time 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

you should use

Calendar.DAY_OF_MONTH

NOT

cal.get(Calendar.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

use it like: cal.set(Calendar.DAY_OF_MONTH,1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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