Search code examples
htmljquerydatetimepicker

HTML5 Datetime-local picker Date and time format to another field


I am currently using the HTML 5 Datetime-local input to get my date and time data which then gets replicated into another input field however when it gets replicated it formats the date and time differently. How am I able to format the date/time before it gets added into the input field?

Datetime-local picker:
enter image description here

Input field:
enter image description here

HTML:

<input id="dt" class="input" type="datetime-local">

jQuery:

$(document).ready(function () {
 $('#dt').on('change', function () {
  $('#datetime').val($(this).val())
 })
})

TIA


Solution

  • You can easily edit the value of your date time local using JavaScript

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    
        <title></title>
      </head>
      <body>
        <label for="datetime">datetime</label>
        <input type="text" name="datetime" id="datetime" value="" />
        <input id="dt" class="input" type="datetime-local" onchange="dateTimeFormat()">
        <script type="text/javascript" charset="utf-8">
          function dateTimeFormat(){
            let unformattedDT = dt.value;
            let processingDate = unformattedDT.replace(/-/g,"/");
            console.log(processingDate);
            
            let list=processingDate.split("T");
            datetime.value =`${list[0]} , ${list[1]}`;
          }
        </script>
      </body>
    </html>