search

Home  >  Q&A  >  body text

Convert date from string to input type date format

<p>I have a "datetime-local" HTML input type which I then store in a datetime field in an MS SQL Server database. When I load the edit page, I want to populate this HTML date field with the value from the database. When I console out the value of the date, it is: "Tuesday, 16 May 2023 15:40:00 GMT 0200 (South African Standard Time)". Has anyone successfully used Javascript to convert a string like this into an acceptable HTML date input format? </p>
P粉587780103P粉587780103471 days ago576

reply all(1)I'll reply

  • P粉788765679

    P粉7887656792023-09-06 19:51:15

    Js has built-in methods that you can use to handle dates.

    In the following example I:

    • Use the Date method to convert the input string into a Date object.
    • Use the getFullYear method to extract the year from the Date object.
    • Use the getMonth method to extract the month from the Date object.
      • Since the getMonth method returns the zero-based month index (January = 0, February = 1, etc.), we must do the following: Result 1.
      • Convert month to string.
      • Use the padStart method to ensure that the month string is 2 characters long. Example: If extracted value = 1, then month = 01.
    • Use the getDay method to extract the date from the Date object.
      • Convert date to string.
      • Use the padStart method to ensure that the date string is 2 characters long. Example: If extracted value = 1, then date = 01.
    • Format the date so it fits the HTML input format.
    • Replace the HTML element value with the value we extracted.

    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>

    reply
    0
  • Cancelreply