174

Does anyone know how I can take a MySQL datetime data type value, such as YYYY-MM-DD HH:MM:SS and either parse it or convert it to work in JavaScript's Date() function, for example:- Date('YYYY, MM, DD, HH, MM, SS);

Thank you!

Zeeshan
  • 493
  • 2
  • 11
  • 25
dzm
  • 22,844
  • 47
  • 146
  • 226

15 Answers15

438

Some of the answers given here are either overcomplicated or just will not work (at least, not in all browsers). If you take a step back, you can see that the MySQL timestamp has each component of time in the same order as the arguments required by the Date() constructor.

All that's needed is a very simple split on the string:

// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);

// Apply each element to the Date function
var d = new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));

console.log(d);
// -> Wed Jun 09 2010 14:12:01 GMT+0100 (BST)

Fair warning: this assumes that your MySQL server is outputting UTC dates (which is the default, and recommended if there is no timezone component of the string).

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 3
    Thank you so much for this elegant solution! I had to use it because Safari doesn't seem to be able to automatically generate a Date object from a MySQL time stamp string eg. `var d = new Date("2010-06-09 13:12:01");`. While interestingly, Chrome has no problem with it. – alnafie Mar 18 '12 at 15:58
  • and to think that other answers where suggesting a more complex solution. Thanks a lot! – R.D. Mar 11 '14 at 00:12
  • This is the wrong answer. The correct answer is posted below by Symen Timmermans. All dates are serialized (stored) as a number that counts either seconds (in the case of unix time stamp) or milliseconds (javascript) since 1970 UTC. Manipulating date strings which are convoluted representations of this number is a waste of resources. Just pass the unix time stamp (multiplied by 1000 for milliseconds) to javascript Date constructor (as suggested by Symen Timmermans) and you have it. – Reinsbrain Apr 22 '14 at 20:16
  • 1
    @Reinsbrain: It's not the wrong answer, just one that didn't suit your requirements. There's a difference. What if the implementer has no access to the server code performing the MySQL query (perhaps some kind of web service)? What if it's easier to edit the client side code because changing it at the server would mean more work? There's no point splitting hairs over a few bytes that could be rendered insignificant by gzipping, or the ten-thousandths of a millisecond required to split a string. – Andy E Apr 22 '14 at 23:02
  • @Andy E: That is true - where there is no access to change the query then your answer solves the problem. – Reinsbrain Apr 23 '14 at 17:06
  • 5
    uh mysql uses one time zone and the javascript Date constructor only accepts the local time zone thus rendering this solution wrong by up to 24 hours... the `new Date(Date.UTC(...))` is better, but that assumes that mysql uses utc... either way this needs to be considered before this can be considered a correct answer. – user3338098 Apr 03 '15 at 14:22
  • @Reinsbrain Agreed, Symen Timmermans answer is better. As user3338098 points out, this answer could be off by 24 hours. – Kellen Stuart Jul 13 '16 at 20:56
  • 1
    @Kolob: I've updated with the `Date.UTC` recommendation. I was torn between whether an author would want dates as they are represented in MySQL or in their local timezone. I concede that the latter is probably more preferable. Thanks :-) – Andy E Jul 14 '16 at 08:14
  • Dude you just relieved 3 days of hair pulling for me, I can't thank you enough – Jacob Broughton Jun 22 '21 at 14:18
  • Just FYI this won't compile under typescript as you're passing in string tokens whereas it should be numbers. – Dean Oct 22 '21 at 06:34
66

To add to the excellent Andy E answer a function of common usage could be:

Date.createFromMysql = function(mysql_string)
{ 
   var t, result = null;

   if( typeof mysql_string === 'string' )
   {
      t = mysql_string.split(/[- :]/);

      //when t[3], t[4] and t[5] are missing they defaults to zero
      result = new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);          
   }

   return result;   
}

In this way given a MySQL date/time in the form "YYYY-MM-DD HH:MM:SS" or even the short form (only date) "YYYY-MM-DD" you can do:

var d1 = Date.createFromMysql("2011-02-20");
var d2 = Date.createFromMysql("2011-02-20 17:16:00");
alert("d1 year = " + d1.getFullYear());
Community
  • 1
  • 1
Marco Demaio
  • 33,578
  • 33
  • 128
  • 159
33

I think I may have found a simpler way, that nobody mentioned.

A MySQL DATETIME column can be converted to a unix timestamp through:

SELECT unix_timestamp(my_datetime_column) as stamp ...

We can make a new JavaScript Date object by using the constructor that requires milliseconds since the epoch. The unix_timestamp function returns seconds since the epoch, so we need to multiply by 1000:

SELECT unix_timestamp(my_datetime_column) * 1000 as stamp ...

The resulting value can be used directly to instantiate a correct Javascript Date object:

var myDate = new Date(<?=$row['stamp']?>);

Hope this helps.

Symen Timmermans
  • 877
  • 1
  • 8
  • 18
  • 4
    Yes, the efficient easy way. But, I would push the multiplication (*1000) of the unix timestamp onto the client (in javascript) – Reinsbrain Apr 22 '14 at 20:52
24

One liner for modern browsers (IE10+):

var d = new Date(Date.parse("2010-06-09 13:12:01"));
alert(d); // Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)

And just for fun, here's a one-liner that will work across older browsers (now fixed):

new (Function.prototype.bind.apply(Date, [null].concat("2010-06-09 13:12:01".split(/[\s:-]/)).map(function(v,i){return i==2?--v:v}) ));
alert(d); // Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)
aleemb
  • 31,265
  • 19
  • 98
  • 114
9

Recent versions of JavaScript will read an ISO8601 formatted date, so all you have to do is change the space to a 'T', doing something like one of the following:

#MySQL
select date_format(my_date_column,'%Y-%m-%dT%T') from my_table;

#PHP
$php_date_str = substr($mysql_date_str,0,10).'T'.substr($mysql_date_str,11,8);

//JavaScript
js_date_str = mysql_date_str.substr(0,10)+'T'+mysql_date_str.substr(11,8);
Jeff
  • 2,095
  • 25
  • 18
3

To add even further to Marco's solution. I prototyped directly to the String object.

String.prototype.mysqlToDate = String.prototype.mysqlToDate || function() {
    var t = this.split(/[- :]/);
    return new Date(t[0], t[1]-1, t[2], t[3]||0, t[4]||0, t[5]||0);
};

This way you can go directly to:

var mySqlTimestamp = "2011-02-20 17:16:00";
var pickupDate = mySqlTimestamp.mysqlToDate();
Adrian Bartholomew
  • 2,506
  • 6
  • 29
  • 37
3

There is a simpler way, sql timestamp string:

2018-07-19 00:00:00

The closest format to timestamp for Date() to receive is the following, so replace blank space for "T":

var dateString = media.intervention.replace(/\s/g, "T");

"2011-10-10T14:48:00"

Then, create the date object:

var date = new Date(dateString);

result would be the date object:

Thu Jul 19 2018 00:00:00 GMT-0300 (Horário Padrão de Brasília)

2

From Andy's Answer, For AngularJS - Filter

angular
    .module('utils', [])
.filter('mysqlToJS', function () {
            return function (mysqlStr) {
                var t, result = null;

                if (typeof mysqlStr === 'string') {
                    t = mysqlStr.split(/[- :]/);

                    //when t[3], t[4] and t[5] are missing they defaults to zero
                    result = new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
                }

                return result;
            };
        });
Community
  • 1
  • 1
jaym
  • 1,253
  • 13
  • 18
2

How to manipulate MySQL timestamp in Javascript

I had to deal with this topic right today

so I have mixed two functions that I'd like to share

function mysqlDatetoJs(mysqlTimeStamp){
    var t = mysqlTimeStamp.split(/[- :]/);
        return new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
    }

and then

function prettyDate(date) {
    var months =  ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu',
                    'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'];

    return date.getUTCDate() + ' ' + months[date.getUTCMonth()] 
    + ' ' + date.getUTCFullYear();
    }

I have used it in building a dynamic table like this

td.innerHTML = prettyDate(mysqlDatetoJs(array[i].data));

and as result in the TD it is printed the date

4 Set 2021

given that array[i].data is the date record from the MySQL table and in particular for this reply it comes in the form

2021-09-04 11:25:20

hope it can be useful

Though I have found a clean date() explanation in this page https://www.digitalocean.com/community/tutorials/understanding-date-and-time-in-javascript

Robert
  • 490
  • 1
  • 5
  • 17
1
var a=dateString.split(" ");
var b=a[0].split("-");
var c=a[1].split(":");
var date = new Date(b[0],(b[1]-1),b[2],b[0],c[1],c[2]);
bhowden
  • 669
  • 7
  • 15
  • +1 for not evoking regular expressions. (Now, if we could just turn it into a oneliner and get rid of the vars...) – T4NK3R Jul 13 '14 at 05:38
1

First you can give JavaScript's Date object (class) the new method 'fromYMD()' for converting MySQL's YMD date format into JavaScript format by splitting YMD format into components and using these date components:

Date.prototype.fromYMD=function(ymd)
{
  var t=ymd.split(/[- :]/); //split into components
  return new Date(t[0],t[1]-1,t[2],t[3]||0,t[4]||0,t[5]||0);
};

Now you can define your own object (funcion in JavaScript world):

function DateFromYMD(ymd)
{
  return (new Date()).fromYMD(ymd);
}

and now you can simply create date from MySQL date format;

var d=new DateFromYMD('2016-07-24');
sbrbot
  • 6,169
  • 6
  • 43
  • 74
1

You can construct a layout like this by using the Js Date() methods before provide your string date to Date object:

 parseDate(date){
         const formated = new Date(date)
         
         return `${formated.getFullYear()}/${formated.getMonth()}/${formated.getDay()}`;
     },
  • Welcome to StackOverflow. While this code may answer the question, providing additional context regarding *how* and/or *why* it solves the problem would improve the answer's long-term value. – Sven Eberth Jun 23 '21 at 22:48
  • 1
    this answer deserves to be the right one, short and efficient – oussama benounnas Jun 29 '21 at 20:15
0

You can use unix timestamp to direct:

SELECT UNIX_TIMESTAMP(date) AS epoch_time FROM table;

Then get the epoch_time into JavaScript, and it's a simple matter of:

var myDate = new Date(epoch_time * 1000);

The multiplying by 1000 is because JavaScript takes milliseconds, and UNIX_TIMESTAMP gives seconds.

bharat
  • 1,762
  • 1
  • 24
  • 32
-3

A quick search in google provided this:

 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]);
  }

Source:http://snippets.dzone.com/posts/show/4132

Stefan Valianu
  • 1,370
  • 2
  • 13
  • 24
-4

Why not do this:

var d = new Date.parseDate( "2000-09-10 00:00:00", 'Y-m-d H:i:s' );
Christian Specht
  • 35,843
  • 15
  • 128
  • 182
josh803316
  • 303
  • 5
  • 10
  • 2
    parseDate is not a JS method of the Date object. Eventually there is a static parse method but it accepts only 1 argument. – Marco Demaio Feb 20 '11 at 16:34