Create Date from MySQL DATETIME format in JavaScript

Dominik Bulaj
ITNEXT
Published in
1 min readJun 11, 2018

--

In JavaScript we can create Date object by either constructor (new Date()) or by using Date.parse() method.

In both cases (optionally) we can provide dateString. MDN notes it should be:

A string representing an RFC2822 or (a variant of) ISO 8601 date (other formats may be used, but results may be unexpected).

Although Chrome browser seems to parse lot of formats, incl. MySQL’s DATETIME (YYYY-MM-DD HH:MM:SS), Safari for example has problem with understanding it and new Date('2017–02–04 11:23:54') results in Invalid Date error.

If you want easily parse MySQL DATETIME to JS Date you can use this technique:

I used regular expression in split to create array with: year, month, day, hour, minute and seconds values.
Since monthIndex in JS Date starts with 0 (January) we need to decrement second value in array by one.

Finally I used spread operator in Date call which just calls Date with 6 parameters: year, month (decremented by one), day, hour, minute and seconds.

UPDATED 29.01.2019

If you need parse just date (YYYY-MM-DD) without time, you can actually use even simpler (and nicer 😎) code:

--

--