Add/subtract days from date calculator

adrianskar

Adrian Skar

Posted on February 1, 2022

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
💖 💪 🙅 🚩
adrianskar
Adrian Skar

Posted on February 1, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Add/subtract days from date calculator
javascript Add/subtract days from date calculator

February 1, 2022