-1

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.

enter image description here

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110

2 Answers2

0

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.

Iziminza
  • 374
  • 3
  • 8
  • It would return `2012-01-12T00:00:00.000Z` which OP doesn't want. – DecPK Jun 13 '21 at 13:33
  • No, it returns a date object. The OP wants to parse a date string into a date object. Only the snippet runtime converts it to this strange string. – Iziminza Jun 13 '21 at 13:42
0

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'));
Sparrow
  • 280
  • 1
  • 12