Search code examples
javascripthtmltypescripthtml-input

Why my time is not showing correct output when submitting?


I am using the below code. Everything is fine, but when I send information it sends in 24-hour format. How can I resolve this? Now it's showing 13:00 I want to show 1:00 PM.

  <!DOCTYPE html>
  <html>
<head>
  <title>Page Title</title>
</head>
<body>
  <input type="time" value=""  id="a_time">
  <input type="button" onclick="gettime();" value="Click Here">
  <script type="text/javascript">
    function gettime(){
      alert(document.getElementById("a_time").value);
    }
  </script>
</body>
  </html>


Solution

  • try this,

    <!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>
    
    <input type="time" value=""  id="a_time">
    <input type="button" onclick="gettime();" value="Click Here">
    <script type="text/javascript">
    function gettime(){
        var v = document.getElementById("a_time").value;
        var r = tConvert (v);
        alert(r);
    }
    
    
    function tConvert (time) {
    
          time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
        
          if (time.length > 1) {
            time = time.slice (1); 
            time[5] = +time[0] < 12 ? 'AM' : 'PM'; 
            time[0] = +time[0] % 12 || 12; 
          }
          return time.join (''); 
    }
    </script>
    </body>
    </html>