P粉7887656792023-09-06 19:51:15
Js has built-in methods that you can use to handle dates.
In the following example I:
Date
method to convert the input string into a Date object. getFullYear
method to extract the year from the Date object. getMonth
method to extract the month from the Date object.
getMonth
method returns the zero-based month index (January = 0, February = 1, etc.), we must do the following: Result 1. padStart
method to ensure that the month string is 2 characters long. Example: If extracted value = 1, then month = 01. getDay
method to extract the date from the Date object.
padStart
method to ensure that the date string is 2 characters long. Example: If extracted value = 1, then date = 01. const input = "Tue May 19 2024 15:40:00 GMT+0200 (South Africa Standard Time)"; const inputDate = new Date(input); const year = inputDate.getFullYear(); const month = (inputDate.getMonth() + 1).toString().padStart(2, "0"); const day = inputDate.getDate().toString().padStart(2, "0"); const formattedDate = `${year}-${month}-${day}`; const datePicker = document.getElementById('datePicker'); datePicker.value = formattedDate;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input type="date" id="datePicker" value=""> </body> </html>