DateTime addmonths method is adding 1 extra day

201 views Asked by At

I am currently working on an issue where DateTime.addMonths(iStartDateH, durationAsInt) is adding an extra day. It uses GeorgianCalendar internally. We are using Java 5 currently in this project Eg: For 24 months

    ExpirationDate=DateTime.addMonths(currentDate, 24)
    CurrentDate= 01/02/2021 (dd/mm/yyyy format)
    ExpirationDate= 02/02/2023
public static ErrorCode addMonths(DateHolder dateH, int numMonths) {
    try {
        Calendar c = new GregorianCalendar();
        c.setTime(dateH.value);
        c.add(Calendar.MONTH, numMonths);
        dateH.value = c.getTime();
        return ErrorCode.successCN;
    }
    catch (Exception e) {
        IlMessage msg = new IlMessage(Msg.exceptionCaughtCN, e);
        IlSession.getSession().getMessageStack().push(msg);
        return ErrorCode.errorCN;
    }
}

I tried checking the complete date/time difference and its coming as 730.773935185185185 Please help with the same.

2

There are 2 answers

1
bhaskar On

I am using Java 8 and I tried the code below and it worked just fine for me (for testing purposes I set the date as Feb 1 as from your example.

    public static void main(String...pStrings) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        LocalDate currentDate = LocalDate.of(2021, 2, 1); //LocalDate.now();
        System.out.println("Original Date -" +currentDate.format(formatter));
        
        LocalDate newDate = currentDate.plusMonths(24);
        System.out.println("updated date - " + newDate.format(formatter));
    }

I received the output: -

Original Date -01/02/2021
updated date - 01/02/2023
0
Arvind Kumar Avinash On
  1. Note that m is for minutes. For a month, you need to use M.
  2. The implementation of your class, DateHolder seems to have a problem. There is no such problem with java.util date-time API for this requirement.

Demo:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH).parse("01/02/2021"));
        System.out.println(calendar.getTime());
        int numMonths = 24;
        calendar.add(Calendar.MONTH, numMonths);
        System.out.println(calendar.getTime());
    }
}

Output:

Mon Feb 01 00:00:00 GMT 2021
Wed Feb 01 00:00:00 GMT 2023