Momentjs: Parse format like 'MM/DD/YYYY hmA' doesn't work

379 Views Asked by At

I have a date string and try to parse it use moment.js:

var d = '06/09/2015 200AM';
var date = moment(d, 'MM/DD/YYYY hmmA');

However, the hour seems not right after parsing:

console.error(date.hours); //output: 20

Am I doing anything wrong here?

I guess if hour and minute are separated by a ':' would solve the problem, but the time was get from value of a and I don't like to put the ':' in it..

Thanks for all the help.

2

There are 2 best solutions below

0
On

That's a very odd string format, one would normally expect a reliable two digits for that hour value. I think you're going to have to pre-process it.

var d = /*...get the string from wherever...*/;
var r = /^(\d{2}\/\d{2}\/\d{4}) (\d{3}..)$/
var m = r.exec(d);
if (m) {
    d = m[1] + " 0" + m[2];
}
var date = moment(d, 'MM/DD/YYYY hmmA');
0
On

Its because '06/09/2015 200AM' is an invalid date so it won't work. Here is a fiddle example of a the invalid datetime next to a valid datetime. Just play with this fiddle to get it right.

http://jsfiddle.net/Luex16af/

If you don't want to fix the date with colon and space. I've updated the fiddle to use javascript to inject the ':' and space for you:

http://jsfiddle.net/Luex16af/1/