Search code examples
javascriptreactjsdatedate-fns

How to rearrange date string from MM DD YYYY to YYYY MM DD?


I tried new Date(03/11/2015) but it didn't work but new Date(2015/3/11) does. How do I convert a string like '03/11/2015' to '2015/3/11'? I tried using date-fns with the format method but format(new Date(03/15/2015), 'YYYY/MM/DD') returns Invalid time value

Why isn't the Date constructor taking in string values in MM/DD/YYYY format?


Solution

  • You could use a regex replacement approach here:

    var input = '03/11/2015';
    var output = input.replace(/(\d+)\/(\d+)\/(\d+)/, "$3/$1/$2");
    var date = new Date(output);
    console.log(date);