How to convert JavaScript datetime to MySQL datetime ?
Given a date in JavaScript DateTime format and 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.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ 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 slice() and
<!DOCTYPE HTML> < html > < head > < title > How to convert JavaScript datetime to MySQL datetime ? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;" > </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to convert " + "the JS datetime to MySQL datetime."; function GFG_Fun() { var date = new Date(); el_down.innerHTML = "MySQL datetime - " + date.toISOString().slice(0, 19).replace('T', ' '); } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Example 2: This is same as previous example but with a different approach and time is in IST, the JS datetime is converted to MySQL datetime by using slice() and replace() method.
<!DOCTYPE HTML> < html > < head > < title > How to convert JavaScript datetime to MySQL datetime ? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;" > </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to convert " + "the JS datetime to MySQL datetime."; function GFG_Fun() { var date = new Date(); el_down.innerHTML = "MySQL datetime - " + date.toISOString().split('T')[0] + ' ' + date.toTimeString().split(' ')[0]; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: