Mmmmmm
Mmmmmm

Reputation: 25

Get yesterday midnight date javascript

I would like to get 2 date variable, one corresponding to midnight yesterday and another corresponding to midnight today. Example: We are on 2021-01-19T10: 42: 00Z. I need :

Yesterday = 2021-01-18T00: 00: 00Z
Today = 2021-01-19T00: 00: 00Z

for that I did:

let date = new Date()
let yesterday = new Date(date.setDate(date.getDate() - 1)).setHours(0,0,0,0)

But this return :

Yesterday = 2021-01-17T23: 00: 00Z

Can someone help me please?

Upvotes: 2

Views: 3182

Answers (1)

Prime
Prime

Reputation: 2849

You can use setUTCHours instead of setHours

const today = new Date();
today.setUTCHours(0,0,0,0);
console.log("Today: ", today);

const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setUTCHours(0,0,0,0);
console.log("Yesterday: ", yesterday);

Upvotes: 6

Related Questions