0

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);
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 1
    This doesn't have much to do with jquery – evolutionxbox May 09 '22 at 15:15
  • 2
    `Date.parse()` is not a general purpose parser. If you know the date format you can write your own parser. If not, you could use `moment.js`. – Barmar May 09 '22 at 15:16
  • The bad news? This is way more complicated than it sounds/should be. The good news? There's about a million million examples of how to do it on this site already. Happy googling! – Jared Smith May 09 '22 at 15:18

2 Answers2

0

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);
delibalta
  • 300
  • 2
  • 11
  • That format isn't even close to [the ISO standard one](https://en.wikipedia.org/wiki/ISO_8601), which is the only one *guaranteed* to work. – Jared Smith May 09 '22 at 15:24
  • 1
    Yes you are right, thank you. I answered the question in this way to at least show the direction to the friend who asked the question :) – delibalta May 09 '22 at 15:27
0

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