30秒学会 JavaScript 片段 · 2024年1月17日

30秒学会 JavaScript 片段 – Date of yesterday, today or tomorrow in JavaScript

In a previous post, we’ve covered Date object manipulation and, most importantly, how to add days to a date. This time around, we’ll take a look at how to calculate the date of yesterday, today and tomorrow, using the same technique.

Date of today

The current date is the easiest to calculate. We can simply use the Date constructor to get the current date.

代码实现

const today = () => new Date();

today().toISOString().split('T')[0];
// 2018-10-18 (if current date is 2018-10-18)

Date of yesterday

To calculate the date of yesterday, we simply need to decrement the current date by one. To do this, we will use Date.prototype.getDate() and Date.prototype.setDate() to get and set the date, respectively.

使用样例

const yesterday = () => {
  let d = new Date();
  d.setDate(d.getDate() - 1);
  return d;
};

yesterday().toISOString().split('T')[0];
// 2018-10-17 (if current date is 2018-10-18)

Date of tomorrow

To calculate the date of tomorrow, we simply need to increment the current date by one, instead of decrementing it.

const tomorrow = () => {
  let d = new Date();
  d.setDate(d.getDate() + 1);
  return d;
};

tomorrow().toISOString().split('T')[0];
// 2018-10-19 (if current date is 2018-10-18)

翻译自:https://www.30secondsofcode.org/js/s/date-yesterday-today-tomorrow