Skip to content

Latest commit

 

History

History
35 lines (29 loc) · 1.21 KB

days-ago-days-from-today.md

File metadata and controls

35 lines (29 loc) · 1.21 KB
title shortTitle type language tags cover excerpt dateModified
How can I find the date of n days ago from today using JavaScript?
Days ago from today
tip
javascript
date
orange-wedges
Calculate the date of `n` days ago from today or the date of `n` days from now.
2024-01-07

As mentioned previously, Date objects in JavaScript act similar to numbers. This means that you can easily add or subtract days from a date by using the Date.prototype.getDate() and Date.prototype.setDate() methods.

Note

I've covered how you can add days to a date in detail. I strongly recommend reading more about the topic, as it can come in handy in many situations.

Using these methods, we can easily calculate the date of n days ago from today. We can also do the same to calculate the date of n days from today.

const daysAgo = n => {
  let d = new Date();
  d.setDate(d.getDate() - Math.abs(n));
  return d;
};

const daysFromToday = n => {
  let d = new Date();
  d.setDate(d.getDate() + Math.abs(n));
  return d;
};

daysAgo(20); // 2023-12-17 (if current date is 2024-01-06)
daysFromToday(20); // 2024-01-26 (if current date is 2024-01-06)