DEV Community

Benjamin Mock
Benjamin Mock

Posted on

JavaScript Dates in SQL

SQL and JS dates are not that compatible.

for the datetime type of MySQL for example you need a date in the following format

"2018-04-21 12:11:01"

The suggestions that you usually find on the internet aren't correct, because they don't tate timezones into consideration.

So this does not work correctly!

new Date().toISOString().slice(0, 19).replace('T', ' ');

You can easily solve the problem by using moment.js

require('moment')().format('YYYY-MM-DD HH:mm:ss');

If you don't want to go this route, you can also solve it without an additional library - it just doesn't read as nicely.

const d = new Date(); 
d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];

Oldest comments (2)

Collapse
 
memodev07 profile image
Guillermo Arias

The last example won't work when the date is in the next day and my timezone is still today.

Collapse
 
induratized profile image
Abhinav Sharma

I guess Benjamin gave his Zone example with ISO.
You can use

${d.getDate()}-${d.getMonth()+1}-${d.getFullYear()} d.toTimeString().split(' ')[0]

, where d = new Date() , to get the local result.