The pit of Calendar New Year's Eve in Java

Above code:

    public static void main(String[] args) throws Exception{
    
    

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(simpleDateFormat.parse("2021-08"));

        calendar.roll(Calendar.MONTH, -5);

        String date = simpleDateFormat.format(calendar.getTime());

        System.out.println("-------------" + date + "-------------");
    }

operation result

-------------2021-03-------------

It can be seen that the date obtained by subtracting 5 months is no problem, but there is a problem when subtracting more than one year, and then try to subtract 20 months

    public static void main(String[] args) throws Exception{
    
    

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(simpleDateFormat.parse("2021-08"));

        calendar.roll(Calendar.MONTH, -20);

        String date = simpleDateFormat.format(calendar.getTime());
        
        System.out.println("-------------" + date + "-------------");
    }

operation result

-------------2021-12-------------

The date is wrong, the correct date should be: 2019-12

Solution: replace the roll method with add, the roll method can only be calculated in the current year, and the add method can be calculated across years

    public static void main(String[] args) throws Exception {
    
    

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(simpleDateFormat.parse("2021-08"));

        calendar.add(Calendar.MONTH, -20);

        String date = simpleDateFormat.format(calendar.getTime());

        System.out.println("-------------" + date + "-------------");
    }

operation result

-------------2019-12-------------

Guess you like

Origin blog.csdn.net/qq_39486119/article/details/119653514