kyrpav
kyrpav

Reputation: 778

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

Upvotes: 2

Views: 361

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40078

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

Upvotes: 5

YoHaRo
YoHaRo

Reputation: 142

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);

Upvotes: 1

Related Questions