1

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?

JaeLeeSo
  • 213
  • 1
  • 4
  • 10

1 Answers1

0

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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Is there a way to remove the leading zeros as well in a single regex? i.e. from 03 to 3 without another replace like replaceAll("^0+", "") – JaeLeeSo Mar 12 '21 at 08:24
  • @JaeLeeSo Please see [this canonical JavaScript answer](https://stackoverflow.com/questions/6676488/remove-leading-zeros-from-a-number-in-javascript). – Tim Biegeleisen Mar 12 '21 at 08:27