3

I am facing this issue with javascript, I get yyyy-mm-dd dates from a database, but when I want to get the number of the week with getDay(), I get a wrong number if the day is with leading zero

getDay() return wrong day if day is with leading zero


I wrote a posible solution to parse MySql date into Javascript Date

function parseDate(str){
  var dt=str.replace(/[-T:]/g," ").split(" ");
  return new Date(dt[0],dt[1]-1,dt[2],dt[3]|0,dt[4]|0,dt[5]|0);
}

parseDate("2018-02-08");
//Thu Feb 08 2018 00:00:00 GMT-0600

parseDate("2018-02-08 22:30:00");
//Thu Feb 08 2018 22:30:00 GMT-0600
Phoxer
  • 413
  • 1
  • 4
  • 15
  • Print the date object itself and the difference would become obvious. – zerkms Feb 08 '18 at 23:40
  • Or do `new Date("2018-2-8").toISOString()`. See [MDN's documentation for the `dateString` overload](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) for more info on why. – Heretic Monkey Feb 08 '18 at 23:44
  • @MikeMcCaughan—no, don't do that. Parsing of non–standard strings is implementation dependent. "2018-2-8" it might be parsed as UTC, local or invalid. – RobG Feb 09 '18 at 22:18
  • You can simplify the parser a bit by splitting on non-digits: `str.split(/\D/)`. ;-) – RobG Feb 09 '18 at 22:22
  • @RobG That was a rejoinder to zerkms' comment, to make it obvious how the `Date` object was parsing that string. – Heretic Monkey Feb 09 '18 at 22:27

0 Answers0