Convert JS date time to MySQL datetime

locoboy picture locoboy · Feb 26, 2011 · Viewed 214.7k times · Source

Does anyone know how to convert JS dateTime to MySQL datetime? Also is there a way to add a specific number of minutes to JS datetime and then pass it to MySQL datetime?

Answer

Gajus picture Gajus · Jun 22, 2012
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
    ('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
    ('00' + date.getUTCDate()).slice(-2) + ' ' + 
    ('00' + date.getUTCHours()).slice(-2) + ':' + 
    ('00' + date.getUTCMinutes()).slice(-2) + ':' + 
    ('00' + date.getUTCSeconds()).slice(-2);
console.log(date);

or even shorter:

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

Output:

2012-06-22 05:40:06

For more advanced use cases, including controlling the timezone, consider using http://momentjs.com/:

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

For a lightweight alternative to , consider https://github.com/taylorhakes/fecha

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