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

1
  • Do you need the solution to work only for the 25th, or for other dates like the 21st, 22nd, etc.? Commented Aug 19, 2018 at 7:58

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You may want to add the full parsing and formatting example: moment('25th May 1912', 'Do MMM YYYY').format('YYYY-MM-D');
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));

3 Comments

That's not going to work for the 21st, 22nd, etc.
@brabster Now it will. I just left that on the person asking question. but anyway, thanks :)
I have tried it without using the parse, but I like this approach.
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)
}

4 Comments

That's not going to work for the 21st, 22nd, etc.
I like it, clean and elegant
Your regular expression is wrong - it's one big character set. You should probably alternate instead, and no need for it to be global.
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.