30秒学会 JavaScript 片段 · 2022年8月16日

30秒学会 JavaScript 片段 – How can I find the date of n days ago from today using JavaScript?

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)

翻译自:https://www.30secondsofcode.org/js/s/days-ago-days-from-today