Home  >  Article  >  Database  >  How to Convert MySQL DateTime Stamp into JavaScript\'s Date Format?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 14:55:01448browse

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

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!

Statement:
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