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