HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I find the date of n days ago from today using JavaScript?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
todayjavascriptdatefromhowfindagothecanusing

Problem

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.

Solution

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)


>
> 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.

Code Snippets

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)

Context

From 30-seconds-of-code: days-ago-days-from-today

Revisions (0)

No revisions yet.