JavaScript Date.toMysql()

Published 15th May 2013

This just came in handy for me. It extends JavaScript’s Date() object and adds a toMysql() function for when you need to convert a JavaScript Date object to a MySQL Datetime format (in UTC).

Date.prototype.toMysql = function(){ var date = this; 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); return date; }; // Usage new Date().toMysql(); // Output: 2013-05-16 11:13:19