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
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
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.
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)
}
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));