Java: Customize adding 1 month to the current date

后端 未结 3 1765
一个人的身影
一个人的身影 2021-01-20 07:15

I\'ve read around and basically I\'ve figured out that the Calendar object is capable of adding 1 month to a date specified by using something like:

Calendar         


        
3条回答
  •  没有蜡笔的小新
    2021-01-20 07:43

    It looks like you want the calendar to roll up to the beginning of the next month if the date of the next month is smaller than the date of the month before it. Here's how we'd do that:

    Calendar cal = Calendar.getInstance();
    int oldDay = cal.get(DAY_OF_MONTH);
    cal.add(Calendar.MONTH, 1);
    
    // If the old DAY_OF_MONTH was larger than our new one, then
    // roll over to the beginning of the next month.
    if(oldDay > cal.get(DAY_OF_MONTH){
      cal.add(Calendar.MONTH, 1);
      cal.set(Calendar.DAY, 1);
    }
    

提交回复
热议问题