0

I am trying to calculate a date from a start date and number of days, so basicly add the number of days to a start date and get an end date. The issue is I get some strange results, but only on one date, I have been a few days now trying to figure this one out.

The function is:

CallculateDateFromDays = function(startDate, days) {
var policy_start_date_array = startDate.split("-");
var policy_start_date = new Date(policy_start_date_array[2], policy_start_date_array[1]-1, policy_start_date_array[0]);
var policy_start_date_add = new Date(policy_start_date.getTime() + ((days-1) * 24 * 60 * 60 * 1000));
var dateString = ("0" + (policy_start_date_add.getDate())).slice(-2) + "-" + ("0" + (policy_start_date_add.getMonth()+1)).slice(-2) + "-" + policy_start_date_add.getFullYear();
return dateString;}

The thing is it works until I use the date "28-10-2012" it gives me back the same date even if I add 2 days.

Any ideas, I am stumped.

coderabbi
  • 2,261
  • 16
  • 18
gringoLoco007
  • 839
  • 2
  • 12
  • 18

4 Answers4

2

On October 28th the time changes from DST to "normal", so the day is not equal 24h. That may cause issues in your code.

Also why (days-1) * 24 * 60 * 60 * 1000? If you set days to 1 the whole expression evaluates to zero...

strah
  • 6,702
  • 4
  • 33
  • 45
2

Likely your local timezone changes because of the end of the daylight saving time.

> new Date(2012, 9, 28)
Sun Oct 28 2012 00:00:00 GMT+0200
> // 48 hours later:
> new Date(new Date(2012, 9, 28) + 2 * 24 * 60 * 60 * 1000)
Mon Oct 29 2012 23:00:00 GMT+0100

Always use the UTC methods!

BTW, adding days is much more easier with setDate, which also works around timezone issues:

function calculateDateFromDays(startDate, days) {
    var datestrings = startDate.split("-"),
        date = new Date(+datestrings[2], datestrings[1]-1, +datestrings[0]);
    date.setDate(date.getDate() + days);
    return [("0" + date.getDate()).slice(-2), ("0" + (date.getMonth()+1)).slice(-2), date.getFullYear()].join("-");
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

There's an easier way to achieve that : http://jsfiddle.net/pjambet/wZEFe/2/

pjam
  • 6,356
  • 5
  • 30
  • 40
0

Use javascript date format:

How to format a JavaScript date

So you don't have to manually try to parse date strings.

Community
  • 1
  • 1
Mohamed Nuur
  • 5,536
  • 6
  • 39
  • 55