I need to convert string "Apr 28 2022 12:00AM" to date. I have tried Date.parse, but it is returning "Nan".
var dtstring = "Apr 28 2022 12:00AM";
var dt = Date.parse(dtstring);
console.log(dt);
I need to convert string "Apr 28 2022 12:00AM" to date. I have tried Date.parse, but it is returning "Nan".
var dtstring = "Apr 28 2022 12:00AM";
var dt = Date.parse(dtstring);
console.log(dt);
On the MDN documentation page it is said:
The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause Date.parse() to return NaN.
So the date format is as follows if we correct and write the code is working
var dtstring = "Apr 28 2022 12:00";
var dt = Date.parse(dtstring);
console.log(dt);
If you can change the string of the date, you could just use the Date constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
So for example:
new Date('2022-04-28T12:00:00');
But if you can't change the string, you'll have to use a javascript library that can parse this date.
Here is an example with date-fns and it's function parse:
parse('Apr 28 2022 12:00 AM', 'MMM dd yyyy p', new Date());
Here is the link of the documentation: https://date-fns.org/v2.28.0/docs/parse