Home >Database >Mysql Tutorial >How to Convert JavaScript Date and Time to MySQL DateTime?
How to Convert JavaScript Date Time to MySQL Datetime
Converting JavaScript date time to MySQL datetime is a common task in web development. Here are a few ways to do it:
1. Using the Date.toISOString() method:
The Date.toISOString() method returns a string representation of the date and time in ISO 8601 format. This format is compatible with MySQL datetime data type.
var date = new Date(); var mysqlDatetime = date.toISOString().slice(0, 19).replace('T', ' ');
2. Using Moment.js library:
Moment.js is a popular JavaScript library for handling dates and times. It provides a convenient way to convert JavaScript date time to MySQL datetime.
require('moment')(); // Import Moment.js var date = moment(); var mysqlDatetime = date.format('YYYY-MM-DD HH:mm:ss');
3. Adding minutes to JavaScript date time:
To add a specific number of minutes to a JavaScript date time before converting it to MySQL datetime, use the setMinutes() method.
date.setMinutes(date.getMinutes() + 30);
This will add 30 minutes to the date object. You can then use any of the above methods to convert it to MySQL datetime.
The above is the detailed content of How to Convert JavaScript Date and Time to MySQL DateTime?. For more information, please follow other related articles on the PHP Chinese website!