Prior to ES6, managing dates could get quite verbose. Especially if we wanted 2-digit padded dates like 05 or wanted to format dates in other ways.

In 2019, the following Javscript idiom for date should serve us well:

const date = new Date();
const [yyyy, mm, dd, hh] = date.toISOString().split(/T|:|-/);

The toISOString() call returns 2019-09-18T13:49:12.775Z which we split() on any of :, -, or T giving us ["2019", "09", "19", "13", "04", "42.732Z"] which we then destructure. We can also destrucutre more selectively:

# get day from the third position, ignore the rest
const [,, dd] = date.toISOString().split(/T|:|-/);

Getting Last Month’s Date

How about moving back a month? Nearly the same. We make use of setDate(0) which sets the date to the last day of the previous month.

const date = new Date(); // Dec 31, 2019
date.setDate(0); // Nov 30, 2019 using "0" shorthand
date.setDate(1); // Nov "1", 2019
const [yyyy, mm, dd, hh] = date.toISOString().split(/T|:|-/);

No more having to deal with padding and getYear(), getHours() or getFullYear() and long winded code like var month = ("0" + (date.getMonth() + 1)).slice(-2). Our idiom serves us well: .toISOString().split(/T|:|-/).

A gotcha in setMonth()

In the code above we used the setDate(0) shorthand, which moves date to the last day of the previous month. This is very convenient. Let’s look at the setMonth() alternative though.

Arguably, our code will be far more legible if we use:

const date = new Date(); // 31 December, 2019
date.setMonth(date.getMonth() - 1); // 1 December, 2019

However, we have introduced a bug as noted above. Moving back a month from Dec 31 took us to Dec 1 so we’re still in the same month! To move to November, we need to be doing this instead:

const date = new Date(); // 31 December, 2019
date.setDate(1); // 1 December, 2019
date.setMonth(date.getMonth() - 1); // 1 November, 2019

Be sure to check the excellent Javascript Dates MDN Reference to learn about the API.