To convert a JavaScript Date
object to a MySQL datetime format, you can use the toISOString
method to get the date in ISO format, and then manipulate the string to fit the MySQL datetime format. Given a date in JavaScript DateTime format the task is to convert this time into MySQL DateTime format using JavaScript.
Approach:
- Use date.toISOString() function to convert the date object into string ISO format i.e. YYYY-MM-DDTHH:mm:ss.sss or ±YYYYYY-MM-DDTHH:mm:ss.sss format.
- Use slice() method to extract the part of a string.
- Use replace() method to replace the ‘T’ character with space ‘ ‘.
Example 1: In this example, the JavaScript DateTime object is converted into MySQL DateTime (UTC format) by using the slice() and replace() method.
function GFG_Fun() {
let date = new Date();
console.log( "MySQL datetime - " +
date.toISOString().slice(0, 19).replace( 'T' , ' ' ));
} GFG_Fun(); |
MySQL datetime - 2023-06-18 03:27:13
Example 2: In this example, time is in IST, the JS datetime is converted to MySQL datetime by using the slice() and replace() method.
function GFG_Fun() {
let date = new Date();
console.log( "MySQL datetime - " +
date.toISOString().split( 'T' )[0] + ' '
+ date.toTimeString().split( ' ' )[0]);
} GFG_Fun(); |
MySQL datetime - 2023-06-18 03:28:31