Home > Database > Mysql Tutorial > How to Convert MySQL DateTime Stamps to JavaScript\'s Date Format?

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

Linda Hamilton
Release: 2024-11-16 19:14:03
Original
586 people have browsed it

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

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

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

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

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!

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