Never been to DZone Snippets before?

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

Convert MySQL DATETIME to JS Date() object (See related posts)

This little function parses mysql datetime and returns Date() object

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

Comments on this post

shantanuo posts on Jul 08, 2007 at 08:59
Useful MySQL function to interact with JavaScript
skeeJay posts on Oct 27, 2007 at 09:57
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.
fest posts on Jun 04, 2008 at 09:54
skeeJay, thanks for noticing that bug. I had fixed that in my code, but the bug persisted in this snippet.

You need to create an account or log in to post comments to this site.


Click here to browse all 5545 code snippets

Related Posts