0

I have one date in string format "dd/MM/yyyy hh:mm tt"

when I try to parse, the result is NaN

var test = Date.parse("15/2/2015 8:20 PM");

undefined

test

NaN

Community
  • 1
  • 1
Alex
  • 8,908
  • 28
  • 103
  • 157

2 Answers2

2

Date expects US dates, so 2/15/2015. You can use a library like moment.js (http://momentjs.com/) to help you parsing international dates. JS does not allow this natively :(

Adrien
  • 1,929
  • 1
  • 13
  • 23
0

Pretty simple to parse without a library. Just break it into parts, fix the hour based on am/pm, then pass the values to the Date constructor (remembering to subtract 1 from the month), e.g.

// Parse dd/MM/yyyy hh:mm tt
function parseDMYHmt(s) {
  let [day, month, year, hour, minute, phase] = s.split(/\W/);
  hour = (hour%12) + (phase.toLowerCase() == 'am'? 0 : 12);
  return new Date(year, month - 1, day, hour, minute);
}

["15/2/2015 8:20 AM",
 "15/2/2015 8:20 PM",
 "15/2/2015 12:00 PM",
 "15/2/2015 12:30 AM"
].forEach(s => console.log(s + ' => ' + parseDMYHmt(s).toString()));
RobG
  • 142,382
  • 31
  • 172
  • 209