DEV Community

Adrian Skar
Adrian Skar

Posted on • Edited on

1 1

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)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay