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.
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);
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);
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');
Or, for a lightweight alternative, use Fecha:
require('fecha').format('YYYY-MM-DD HH:mm:ss');
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!