DEV Community

Adrian Skar
Adrian Skar

Posted on • Edited on

Add/subtract days from date calculator

So I wondered when the #301DaysOfCode challenge would end because I started yesterday and built a small add/subtract days calculator.
As it turns out you can easily "add" days to a date using .setDate() but you better remember that its actual purpose is to set the day of the month rather than sum days. Both of the following options seem to work well:

  • "Dirty" but short:
resultDate.setDate(days + 1);
Enter fullscreen mode Exit fullscreen mode
  • "Proper" solution:
resultDate.setDate(resultDate.getDate() + days);
Enter fullscreen mode Exit fullscreen mode



Side note: on a terminal you can just use things like:

date --date="301 days"
date --date="301 days ago"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)