18

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?

2

4 Answers 4

28

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

Sign up to request clarification or add additional context in comments.

1 Comment

its possible to insert AM Or PM like this <input type="time" value="08:56 AM"> <input type="time" value="08:56 PM">
4

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 :)

Comments

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.

Comments

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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.