Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a mySQL date to Javascript date

What would be the best way to convert a mysql date format date into a javascript Date object?

mySQL date format is 'YYYY-MM-DD' (ISO Format).

like image 474
Mike Valstar Avatar asked Sep 06 '25 03:09

Mike Valstar


2 Answers

Given your clarification that you cannot change the format of the incoming date, you need something like this:

var dateParts = isoFormatDateString.split("-");
var jsDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2].substr(0,2));

Original response:

Is there a reason you can't get a timestamp instead of the date string? This would be done by something like:

 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.

like image 66
jhurshman Avatar answered Sep 07 '25 20:09

jhurshman


The shortest and fast method:

var mySQLDate = '2015-04-29 10:29:08';
new Date(Date.parse(mySQLDate.replace(/-/g, '/')));
like image 21
Jonas Sciangula Street Avatar answered Sep 07 '25 19:09

Jonas Sciangula Street