Home > Database > Mysql Tutorial > How to Convert JavaScript DateTime to MySQL DateTime?

How to Convert JavaScript DateTime to MySQL DateTime?

Patricia Arquette
Release: 2024-12-04 13:49:10
Original
440 people have browsed it

How to Convert JavaScript DateTime to MySQL DateTime?

Convert JS DateTime to MySQL DateTime

JavaScript and MySQL employ different date and time formats, making direct conversions necessary. This guide provides various approaches to convert JavaScript's dateTime format to MySQL's compatible format.

Conversion Method

To convert a JavaScript dateTime object to the MySQL datetime format, use the following steps:

// Create a new Date object
var date = new Date();

// Format the date as a string in MySQL's datetime format
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);
Copy after login

Adding Minutes to JS DateTime

To add a specific number of minutes to a JS dateTime object before passing it to MySQL, follow these steps:

// Create a new Date object
var date = new Date();

// Add the desired number of minutes to the date
date.setMinutes(date.getMinutes() + 10);

// Format the date as a string in MySQL's datetime format
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);
Copy after login

Alternative Libraries

For more advanced scenarios, consider utilizing third-party libraries like Moment.js for precise timezone handling:

require('moment')().format('YYYY-MM-DD HH:mm:ss');
Copy after login

Or, for a lightweight alternative, use Fecha:

require('fecha').format('YYYY-MM-DD HH:mm:ss');
Copy after login

The above is the detailed content of How to Convert JavaScript DateTime to MySQL DateTime?. For more information, please follow other related articles on the PHP Chinese website!

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