Converting MySQL DateTime Stamps to JavaScript's Date Format
MySQL's datetime data type stores timestamps in a specific format (YYYY-MM-DD HH:MM:SS). To utilize these timestamps in JavaScript's Date() function, which follows a different date format, a conversion is necessary.
One straightforward approach is to split the MySQL datetime stamp into its individual components using a regular expression:
var t = "2010-06-09 13:12:01".split(/[- :]/);
This results in an array containing the year, month (zero-indexed), day, hour, minute, and second.
Next, use these components as arguments to the Date() constructor:
var d = new Date(Date.UTC(t[0], t[1] - 1, t[2], t[3], t[4], t[5]));
The UTC constructor is used here, assuming the MySQL timestamp is in UTC format (which is the default). Note that the month index is decremented by 1 to match JavaScript's zero-indexed month format.
Finally, the converted date can be accessed through the 'd' variable:
console.log(d); // Output: "Wed Jun 09 2010 14:12:01 GMT+0100 (BST)"
It's important to ensure that the MySQL server is outputting UTC dates to prevent any timezone-related issues in JavaScript.
The above is the detailed content of How to Convert MySQL DateTime Stamps to JavaScript\'s Date Format?. For more information, please follow other related articles on the PHP Chinese website!