Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get AM/PM from HTML time input

First, I know that <input type="time"> is not supported by IE10 or earlier, and Firefox, but this is only for testing purposes and I will make appropriate, cross-browser changes at another time.

For the time being, I have a HTML time input field. I am trying to extract the values from it including the hour, minutes and AM/PM. I can display the hour and minutes, but an AM/PM indication is not including.

I have an input as follows:

<input type="time" name="end-time" id="end-time">

I print out via alert() the input value as follows:

alert(document.getElementById('end-time').value);

Upon input I receive an alert such as:

01:34.

Notice that an AM/PM is not included in the alert().

How can I get the AM/PM value from a HTML time input via Javascript?

like image 294
SamSmith Avatar asked Sep 03 '16 19:09

SamSmith


People also ask

How do you get AM or PM from input type time?

If you want the time with AM & PM, check the first two values, and utilize something like the following: if(FirstTwoNums > 12){ FirstTwoNums -= 12; PM = true;}/*else, PM is false */ .

Is there a time input HTML?

The <input type="time"> defines a control for entering a time (no time zone).

How can input field be used to display current time?

var date = new Date(); var currentDate = date. toISOString(). slice(0,10); var currentTime = date.


2 Answers

As far as i know, We cannot get the value from the input directly in the meridian format of 'AM/PM'. Instead, we can write our own logic of converting the value in the AM/PM format and store/display it.

Below is the implementation of it.

var inputEle = document.getElementById('timeInput');


function onTimeChange() {
  var timeSplit = inputEle.value.split(':'),
    hours,
    minutes,
    meridian;
  hours = timeSplit[0];
  minutes = timeSplit[1];
  if (hours > 12) {
    meridian = 'PM';
    hours -= 12;
  } else if (hours < 12) {
    meridian = 'AM';
    if (hours == 0) {
      hours = 12;
    }
  } else {
    meridian = 'PM';
  }
  alert(hours + ':' + minutes + ' ' + meridian);
}
<input type="time" onchange="onTimeChange()" id="timeInput" />
like image 149
Nikhilesh Shivarathri Avatar answered Oct 19 '22 02:10

Nikhilesh Shivarathri


function print() {
  t = document.getElementById('time').value
  var [h,m] = t.split(":");
  console.log((h%12+12*(h%12==0))+":"+m, h >= 12 ? 'PM' : 'AM');
}
<input type="time" id="time">
<button onclick="print()">Submit</button>

Does this work for you?

like image 29
StardustGogeta Avatar answered Oct 19 '22 02:10

StardustGogeta