Convert MySQL DateTime Stamp to JavaScript's Date Format
Converting a MySQL datetime data type value to JavaScript's Date() function's format can be done with relative ease. The key insight is that the order of time components in the MySQL timestamp matches the order of arguments required by the Date() constructor.
To convert a MySQL datetime string like "YYYY-MM-DD HH:MM:SS" to a JavaScript Date object, simply split the string on dashes and colons:
var t = "2010-06-09 13:12:01".split(/[- :]/);
This will give you an array t with elements representing [Y, M, D, h, m, s].
Now, directly apply each element from t to the Date() constructor:
var d = new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));
The resulting d will be a JavaScript Date object representing the original MySQL datetime value.
console.log(d); // Logs "Wed Jun 09 2010 14:12:01 GMT+0100 (BST)"
Note: This assumes that your MySQL server is outputting UTC dates, which is typically the default behavior. If there is a timezone component in the MySQL datetime string, you may need to adjust the conversion accordingly.
The above is the detailed content of How to Convert MySQL DateTime Stamp to JavaScript\'s Date Format?. For more information, please follow other related articles on the PHP Chinese website!