What's the difference between adding DAY_OF_MONTH or DAY_OF_YEAR to a Calendar object?

前端 未结 10 1372
星月不相逢
星月不相逢 2020-12-08 01:42

I want to increase a certain date by 1 day. I create a Calendar object like:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2012);
cal.set(Cal         


        
10条回答
  •  感动是毒
    2020-12-08 02:33

    Calendar.add Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.

    Here you have a list of the fields of Calendar that you can add or subtract:

    • MILLISECOND is the number of milliseconds between 0 and 999

    • SECOND is the number of seconds between 0 and 59

    • MINUTE is the number of minutes between 0 and 59

    • HOUR is the number of hours between 0 and 11

    • HOUR_OF_DAY is the number of hours between 0 and 23

    • DAY_OF_WEEK is the day in relation of the week between 1 and 7

    • DAY_OF_MONTH is the day in relation of the month between 1 and 31

    • DAY_OF_YEAR is the day in relation of the year between 1 and 365

    • WEEK_OF_MONTH is the week in relation of the month starting from 1

    • WEEK_OF_YEAR is the week in relation of the year starting from 1

    • MONTH is the month in relation of the year between 0 and 11

    • YEAR is the number of years starting from 1

    Hours, days and weeks have multiple fields but it doesn't matter which one you choose1. For example using -8 for DAY_OF_WEEK will work.

    calendar.add(Calendar.DAY_OF_MONTH, -2); // subtract 2 days
    calendar.add(Calendar.DAY_OF_WEEK, -2);  // subtract 2 days
    calendar.add(Calendar.DAY_OF_YEAR, -2);  // subtract 2 days
    
    calendar.add(Calendar.YEAR, -2);         // subtract 2 years
    

    1It doesn't matter only using Calendar.add, with other operations the results might be different.

提交回复
热议问题