Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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());

about 4 years ago · Juan Pablo Isaza Report

0

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());

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!