17

I have a form with input type time. I am trying to set values. But it is not showing. Here is my code.

<input type="time" name="exit" id="teacher-entry-exit-form-exit-input" class="form-control" value="08:56 AM" required="">

What am I doing wrong?

halfer
  • 19,824
  • 17
  • 99
  • 186
odbhut.shei.chhele
  • 5,834
  • 16
  • 69
  • 109

4 Answers4

27

It's based on 24-hour time, therefore use value="08:56" for AM and value="20:56" for PM.

Example Here

<input type="time" value="08:56">

See: http://www.w3.org/TR/html-markup/input.time.html

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
3

Stephen, Giri, all you have to do, in order to get AM/PM set, is to convert your 12-hour time string into 24-hour one, before passing it to the value attribute of input [type=time].

Here is a quick example how to convert 12-hour -> 24-hour time string.

const am_pm_to_hours = time => {
    let hours = Number(time.match(/^(\d+)/)[1]);
    let minutes = Number(time.match(/:(\d+)/)[1]);
    const AMPM = time.match(/\s(.*)$/)[1];
    if (AMPM.toLowerCase() === "pm" && hours < 12) hours = hours + 12;
    if (AMPM.toLowerCase() === "am" && hours == 12) hours = hours - 12;

    let sHours = hours.toString();
    let sMinutes = minutes.toString();
    if (hours < 10) sHours = "0" + sHours;
    if (minutes < 10) sMinutes = "0" + sMinutes;

    return `${sHours}:${sMinutes}`;
}

hope this helps :)

2

This worked for me :

<input class="form-control" type="time" name="time" value="<?=date("H:i", strtotime($dbObject['time'])); ?>" />

In this way, one can fetch the time column and display it like this using PHP and mysql.

rahim.nagori
  • 636
  • 8
  • 20
2

Convert AM/PM Time string to 24 Hours Format. Example 9:30 PM to 21:30

function convertTimeFrom12To24(timeStr) {
  var colon = timeStr.indexOf(':');
  var hours = timeStr.substr(0, colon),
      minutes = timeStr.substr(colon+1, 2),
      meridian = timeStr.substr(colon+4, 2).toUpperCase();
    
  var hoursInt = parseInt(hours, 10),
      offset = meridian == 'PM' ? 12 : 0;
  
  if (hoursInt === 12) {
    hoursInt = offset;
  } else {
    hoursInt += offset;
  }
  return hoursInt + ":" + minutes;
}
console.log(convertTimeFrom12To24("12:00 AM"));
console.log(convertTimeFrom12To24("12:00 PM"));
console.log(convertTimeFrom12To24("11:00 AM"));
console.log(convertTimeFrom12To24("01:00 AM"));
console.log(convertTimeFrom12To24("01:00 PM"));
Malik Zahid
  • 593
  • 5
  • 13