Home > Database > Mysql Tutorial > body text

How to Convert MySQL DateTime Stamp to JavaScript\'s Date Format?

Linda Hamilton
Release: 2024-11-20 03:42:02
Original
340 people have browsed it

How to Convert MySQL DateTime Stamp to JavaScript's Date Format?

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(/[- :]/);
Copy after login

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]));
Copy after login

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)"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template