user8297969
user8297969

Reputation: 455

How to get last day of previous month using current date?

I'm trying to get the last of day of previous month using the current date:

var myDate = new Date();

According to MDN:

if 0 is provided for dayValue, the date will be set to the last day of the previous month.

But when set date to zero:

myDate.setDate(0)
console.log(JSON.stringify(myDate));

I get "2021-08-01T01:18:34.021Z" which first day of the current month. What is wrong with this approach?

Upvotes: 1

Views: 2166

Answers (3)

armonp
armonp

Reputation: 11

You can use date-fns package

var df = require("date-fns")

let myDate = new Date() //Thu Aug 05 2021 22:16:09

let lastDayOfPrevMonth = df.endOfMonth(df.subMonths(myDate, 1)) //Sat Jul 31 2021 23:59:59 GMT-0400

Upvotes: 1

StackSlave
StackSlave

Reputation: 10627

I would use dateInstance.toString() or dateInstance.toLocaleString():

const myDate = new Date;
myDate.setDate(0); myDate.setHours(0, 0, 0, 0);
console.log(myDate.toString()); console.log(myDate.toLocaleString());

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361565

JSON.stringify() is serializing the timestamp with a Z timezone, indicating UTC. The difference between UTC and your local timezone is causing the date to rollover to the next day.

You can use toLocaleString() to print the date in your local timezone:

var myDate = new Date();
myDate.setDate(0);
console.log(myDate.toLocaleString());

Upvotes: 1

Related Questions