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);
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);
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', ' ');
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!