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

Date of yesterday, today or tomorrow in JavaScript

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

Problem

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.
The current date is the easiest to calculate. We can simply use the Date constructor to get the current date.
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.
To calculate the date of tomorrow, we simply need to increment the current date by one, instead of decrementing it.

Solution

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

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


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.
To calculate the date of tomorrow, we simply need to increment the current date by one, instead of decrementing it.

Code Snippets

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

today().toISOString().split('T')[0];
// 2018-10-18 (if current date is 2018-10-18)
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)
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)

Context

From 30-seconds-of-code: date-yesterday-today-tomorrow

Revisions (0)

No revisions yet.