I want to know how to get a date from date string:
A string is expected to be formatted as follows: YYYY-DD-MM
September 01, 2021 would be: 2021-01-09
it should be done using functions in Java Script.
Any answers??
And Thank you in advance.
I want to know how to get a date from date string:
A string is expected to be formatted as follows: YYYY-DD-MM
September 01, 2021 would be: 2021-01-09
it should be done using functions in Java Script.
Any answers??
And Thank you in advance.
 
    
     
    
    Call new Date() on your date string. Like so:
console.log(new Date('2012-01-12'));
Unfortunately for you, in your date format the month is in the end, but new Date() expects it in the middle. In that case, I would use a regular expression:
var a = '2012-01-12'.match(/(\d+)-(\d+)-(\d+)/);
console.log(new Date(a[1], a[3]-1, a[2]));Note that here you have to subtract one from the month, since in JS January is month 0 etc.
 
    
    Try this function it might help you.
function newDateFormat(date) {
    date = new Date(date);
    if(date == 'Invalid Date') return date;
    let month = date.getMonth();
    let day = date.getDate();
    return `${date.getFullYear()}-${day<10?'0':''}${day}-${month<10?'0':''}${month+1}`;
}
console.log(newDateFormat('September 01, 2021'));