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?
Advertisement
Answer
JavaScript
x
10
10
1
var date;
2
date = new Date();
3
date = date.getUTCFullYear() + '-' +
4
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
5
('00' + date.getUTCDate()).slice(-2) + ' ' +
6
('00' + date.getUTCHours()).slice(-2) + ':' +
7
('00' + date.getUTCMinutes()).slice(-2) + ':' +
8
('00' + date.getUTCSeconds()).slice(-2);
9
console.log(date);
10
or even shorter:
JavaScript
1
2
1
new Date().toISOString().slice(0, 19).replace('T', ' ');
2
Output:
JavaScript
1
2
1
2012-06-22 05:40:06
2
For more advanced use cases, including controlling the timezone, consider using http://momentjs.com/:
JavaScript
1
2
1
require('moment')().format('YYYY-MM-DD HH:mm:ss');
2
For a lightweight alternative to momentjs, consider https://github.com/taylorhakes/fecha
JavaScript
1
2
1
require('fecha').format('YYYY-MM-DD HH:mm:ss')
2