Getting wrong date when I add months

557 Views Asked by At

I am writing my stubs in StubbyDB. And asserting the data in functional tests. This is something I am doing in my functional tests to calculate date for assertion (using joda datetime library)

DateTime now = DateTime.now();
DateTime future = now.plusMonths(6);

And this is something I am doing in my stubs;

{{TODAY+6m}}

But I am getting the difference of few days. Is this the bug or am I doing something wrong?

Edit

Consider today is "30 Sept 2016", and I add 5 months to it then

now.plusMonths(5) => 2017-02-28
{{TODAY+5m}} => 2017-03-02
4

There are 4 best solutions below

0
On BEST ANSWER

Reason

As per joda-time documentation,

2007-03-31 plus one month cannot result in 2007-04-31, so the day of month is adjusted to 2007-04-30.

However StubbyDB use javascript based date calculation which adjust date 2007-04-31 to 2007-05-01.

So this is not the bug but this is how these APIs work.

Solution

Found in sample application

use {{JODA_TODAY+6m}} instead of {{TODAY+6m}}

0
On

if you start with 30/09/2016 and add five months you get 30/02/2017.

But February only has 28 days.

It looks like Jodatime has "rounded down" to give you the maximum valid date for the month (i.e 28th Feb) whereas the other library/code is treating "30th Feb" as 2nd March (since that is technically two days past the 28th, which the 30th would also be).

Both are valid assumptions for handling dates IMHO and are a good lesson in why date handling is hard. You'll need to be explicit about which convention you want to follow and you may have to code your assertions to follow Jodatime's conventions.

0
On

See: DateTime::plusMonths(int)

Returns a copy of this datetime plus the specified number of months.

The calculation will do its best to only change the month field retaining the same day of month. However, in certain circumstances, it may be necessary to alter smaller fields. For example, 2007-03-31 plus one month cannot result in 2007-04-31, so the day of month is adjusted to 2007-04-30.

So, 30 Sept 2016 + 5 months = 28 Feb 2017 (according to Joda's logic) and it is not a bug

0
On

Here is sample code for adding months to given calendar date

public class Demo {

 // create a calendar
 Calendar cal = Calendar.getInstance()

// print current date
 System.out.println("The current date is : " + cal.getTime());

 // add 1 months from the calendar
 cal.add(Calendar.MONTH, 1);

}

FYR How to add one month to a date and get the same day