Home > Database > Mysql Tutorial > How to Convert JavaScript Date and Time to MySQL DATETIME Format?

How to Convert JavaScript Date and Time to MySQL DATETIME Format?

Linda Hamilton
Release: 2024-12-15 13:59:25
Original
870 people have browsed it

How to Convert JavaScript Date and Time to MySQL DATETIME Format?

Converting JavaScript Date and Time to MySQL Datetime

When working with dates and time across different technologies, such as JavaScript and MySQL, it becomes necessary to convert them into a compatible format. To convert JS datetime to MySQL datetime, you can apply the following steps:

var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
    ('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
    ('00' + date.getUTCDate()).slice(-2) + ' ' + 
    ('00' + date.getUTCHours()).slice(-2) + ':' + 
    ('00' + date.getUTCMinutes()).slice(-2) + ':' + 
    ('00' + date.getUTCSeconds()).slice(-2);
console.log(date);
Copy after login

This code snippet creates a new Date object, extracts the individual components, formats them with leading zeros for single-digit values, and then assembles them into a MySQL datetime string.

To add a specific number of minutes to the JS datetime before converting it, you can use the following approach:

date.setMinutes(date.getMinutes() + minutesToAdd);
Copy after login

Once you have modified the date accordingly, you can then use the same conversion process mentioned above. Alternatively, you can use a more concise version:

new Date().toISOString().slice(0, 19).replace('T', ' ');
Copy after login

For more advanced scenarios, such as controlling the timezone, consider using libraries like momentjs or fecha for greater flexibility and powerful formatting options.

The above is the detailed content of How to Convert JavaScript Date and Time to MySQL DATETIME 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