1

I am trying to reformat the string date to date as mentioned below:

'25th May 1912' → 1912-05-2

I tried with Date.parse() but it throws an error.

Any suggestions?

Thanks

Srinivas
  • 1,516
  • 3
  • 17
  • 27

3 Answers3

4

JavaScript's built-in date parsing is very limited, it doesn't support many formats.

As suggested by the documentation linked above, I would use a library to parse this format, such as momentjs, unless there was a reason not to (page load times, etc.).

I think the following will parse and reformat it:

moment("25th May 1912", "Do MMM YYYY").format("YYYY-MM-DD");

It'll also parse variations like "21st May 1912" that might cause bugs in simple hand-rolled implementations.

Using a library helps avoid bugs you might not have thought of and avoids growing nasty, hard to read string hacking code in your application.

brabster
  • 42,504
  • 27
  • 146
  • 186
  • 1
    You may want to add the full parsing and formatting example: `moment('25th May 1912', 'Do MMM YYYY').format('YYYY-MM-D');` – dereli Aug 19 '18 at 08:02
1

console.log( parse('25st May 1912') )
console.log( parse('2nd September 2018') )
console.log( parse('6th January 2015') )

function parse(str) {
  let replaced = str.replace(/(th|st|nd|rd)/, '')
  let date = new Date(Date.parse(replaced))
  
  return date.toISOString().slice(0, 10)
}
  • That's not going to work for the 21st, 22nd, etc. – brabster Aug 19 '18 at 07:55
  • I like it, clean and elegant – Andrei Voicu Aug 19 '18 at 07:58
  • Your regular expression is wrong - it's one big character set. You should probably alternate instead, and no need for it to be global. – CertainPerformance Aug 19 '18 at 08:14
  • Relying on the built–in parser is never a good idea. What should `parse('29th February 2019')` return? See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 28 '20 at 09:12
1

You should remove th from your date, Date.parse returns NaN because of it. This should work:

var input = '25th May 1912';
var validInput = input.replace(/(th|st|nd|rd)/, '');
var dateObj = new Date(Date.parse(validInput))
console.log(dateObj.getFullYear() + '-' + ('0' + (dateObj.getMonth()+1)).slice(-2) + '-' + ('0' + dateObj.getDate()).slice(-2));
Pal Singh
  • 1,964
  • 1
  • 14
  • 29