DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Reinis has posted 8 posts at DZone. View Full User Profile

Convert MySQL DATETIME To JS Date() Object

  • submit to reddit
        This little function parses mysql datetime and returns Date() object

  function mysqlTimeStampToDate(timestamp) {
    //function parses mysql datetime string and returns javascript Date object
    //input has to be in this format: 2007-06-05 15:26:02
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);


Reinis Veips replied on Tue, 2007/06/12 - 11:00am

skeeJay, thanks for noticing that bug. I had fixed that in my code, but the bug persisted in this snippet.

Snippets Manager replied on Sat, 2007/10/27 - 9:53am

Thanks very much for the function, I use it constantly in one of my apps. But I think there's a small bug that I had to fix before I could use it. JavaScript's Date() function takes, for its second argument, a month value of 0-11, not the standard 1-12 values that MySQL uses. I think the second argument of Date() in the return line should be parts[1]-1.

Snippets Manager replied on Mon, 2012/05/07 - 2:39pm

Useful MySQL function to interact with JavaScript