Convert MySQL DateTime Stamp into JavaScript's Date Format
Manipulating MySQL datetime values within JavaScript's Date() function can be a challenge. To simplify this process, let's explore a pragmatic solution that requires minimal parsing or conversion.
Solution:
The MySQL datetime string is in "YYYY-MM-DD HH:MM:SS" format, which conveniently matches the order of the arguments expected by the Date() constructor. By splitting the string at each delimiter, we can extract individual time components.
// Split timestamp into [ Y, M, D, h, m, s ] var timestamp = "2010-06-09 13:12:01".split(/[- :]/); // Apply each element to the Date function var date = new Date(Date.UTC(timestamp[0], timestamp[1] - 1, timestamp[2], timestamp[3], timestamp[4], timestamp[5])); console.log(date); // Output: Wed Jun 09 2010 14:12:01 GMT+0100 (BST)
This approach is straightforward and doesn't introduce unnecessary complexity. It assumes that the MySQL server is outputting UTC dates, which is the default and recommended setting for consistency.
The above is the detailed content of How to Convert MySQL DateTime Stamp into JavaScript\'s Date Format?. For more information, please follow other related articles on the PHP Chinese website!