Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Calendar 31st January issue

Tags:

java

I have the following code :-

        Calendar calc = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("MMM-yyyy");
        calc.set(Calendar.YEAR, calc.get(Calendar.YEAR) - 1);
        calc.set(Calendar.MONTH, Calendar.NOVEMBER);
        System.out.println("---NOV? : " + sdf.format(calc.getTime()));

        Calendar calc1 = Calendar.getInstance();
        calc1.set(Calendar.YEAR, calc1.get(Calendar.YEAR) - 1);
        calc1.set(Calendar.MONTH, Calendar.DECEMBER);
        System.out.println("-- DEC : " + sdf.format(calc1.getTime()));

The output of the above code is :-

> ---NOV? : Dec-2012
> -- DEC : Dec-2012

This happens only for 31st january, can someone explain why this might be happening?

like image 236
pranky64 Avatar asked Jun 11 '26 13:06

pranky64


1 Answers

The Calendar is set for lenient interpretation, so if you tell it the 31st day of November, well, November only has 30 days, so it rolls over to December 1st.

like image 105
Affe Avatar answered Jun 14 '26 04:06

Affe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!