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

208
Views
javascript consistent format of date

I have a function that is expecting the startDate and endDate to be in YYYY-mm-dd format as a (String). Because I'm using a couple components/plugins, sometimes the dates are coming in different formats.

If the date comes in as "Wed Jan 01 2020 00:00:00 GMT-0800" format. I want to convert it into YYYY-mm-dd However, if its already in YYYY-mm-dd format, don't touch it.

I tried using something like where I pass in my initial string, but it seems to be messing up my date because of the inconsistent nature of the startDate value.

var d = new Date(startDate);

var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can easily achive the data in YYYY-mm-dd format using toISOString and split

function getDate(date) {
  return date.match(/^\d{4}-\d{2}-\d{2}$/)
    ? date
    : new Date(date).toISOString().split("T")[0];
}

console.log(getDate("2020-03-12"));
console.log(getDate("Wed Jan 01 2020 00:00:00 GMT-0800"));
console.log(getDate("Wed Dec 01 2020 00:00:00 GMT-0800"));
console.log(getDate("Wed Mar 29 2020 00:00:00 GMT-0800"));

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!