May 14, 2013

JavaScript Date.toMysql()

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

Looking for more?

Subscribe to my newsletter to get infrequent updates in your inbox. Or follow me on Twitter.