Java: Customize adding 1 month to the current date

后端 未结 3 1743
一个人的身影
一个人的身影 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);
    }
    
    0 讨论(0)
  • 2021-01-20 07:56

    What you are asking for is some implicit knowledge that if the starting date is the last day of the month, and you add 1 month, the result should be the last day of the following month. I.e. the property "last-day-of-month" should be sticky.

    This is not directly available in Java's Calendar, but one possible solution is to use Calendar.getActualMaximum(Calendar.DAY_OF_MONTH) to reset the day after incrementing the month.

    Calendar cal = ...;
    cal.add(Calendar.MONTH,1);
    cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    

    You could even subclass GregorianCalendar and add a method

    public Calendar endOfNextMonth() { ... }
    

    to encapsulate the operation.

    0 讨论(0)
  • 2021-01-20 08:05

    Well for add 30 days you can do something like this:

    public static java.sql.Date sumarFechasDias(java.sql.Date fch, int days) {
        Calendar cal = new GregorianCalendar();
        cal.setTimeInMillis(fch.getTime());
        cal.add(Calendar.DATE, days);
        return new java.sql.Date(cal.getTimeInMillis());
    }
    

    if days=30, it will return your date with 30 days added.

    0 讨论(0)
提交回复
热议问题