Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  47] [ 2]  / answers: 1 / hits: 22857  / 8 Years ago, tue, august 2, 2016, 12:00:00

I have this very simple code, and it works sometimes but other times it gives the complete wrong date:



  addDays(date: Date, days: number): Date {
console.log('adding ' + days + ' days');
console.log(date);
date.setDate(date.getDate() + days);
console.log(date);
return date;
}


Here is an example of the output:



Works!



adding 7 days
error-chart.component.ts:118 Tue Aug 02 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Tue Aug 09 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))


Stops working:



adding 14 days
error-chart.component.ts:118 Tue Aug 02 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Thu Mar 02 2017 00:00:00 GMT+0100 (Vest-Europa (normaltid))


somehow jumps 2 years



adding 14 days
error-chart.component.ts:118 Thu Jul 07 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Thu Jun 14 2018 00:00:00 GMT+0200 (Vest-Europa (sommertid))


now 4 years!



adding 14 days
error-chart.component.ts:118 Thu Jun 14 2018 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Thu Apr 14 2022 00:00:00 GMT+0200 (Vest-Europa (sommertid))

More From » date

 Answers
23

You have a problem with types. If days is 14, then it will yield 16th August correctly. However, if days is 14, then it will yield 2nd of March.



Solution:



  addDays(date: Date, days: number): Date {
console.log('adding ' + days + ' days');
console.log(date);
date.setDate(date.getDate() + parseInt(days));
console.log(date);
return date;
}

[#61178] Friday, July 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
xiomara

Total Points: 378
Total Questions: 90
Total Answers: 104

Location: Guernsey
Member since Thu, Oct 7, 2021
3 Years ago
;