get yesterday's date in javascript

There are multiple ways to get yesterday's date in JavaScript, one way is to use the Date object and subtract one day from the current date. Another way is to use the Moment.js library which provides more flexibility with formatting and timezone handling.

Here's an example using the Date object:

index.tsx
const today = new Date();
const yesterday = new Date(today);

yesterday.setDate(yesterday.getDate() - 1);

console.log(yesterday);
131 chars
7 lines

Output:

index.tsx
Thu May 06 2021 13:47:05 GMT-0400 (Eastern Daylight Time)
58 chars
2 lines

And here's an example using Moment.js:

index.tsx
const yesterday = moment().subtract(1, 'days');

console.log(yesterday.format());
82 chars
4 lines

Output:

index.tsx
2021-05-06T13:47:05-04:00
26 chars
2 lines

Note that Moment.js provides a formatted timestamp in ISO 8601 format with timezone offset, which can be customized based on your needs.

gistlibby LogSnag