7

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?

SamSmith
  • 167
  • 1
  • 3
  • 13
  • 1
    The returned result is in the form of a 24 hour clock, not a 12 hour clock. 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 */`. There might be a better way, but you can use `parseInt` after you split the time value string to get the hour value as an integer; thus allowing it to be used in the aforementioned conditional. – Spencer D Sep 03 '16 at 19:52

5 Answers5

12

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" />
Nikhilesh Shivarathri
  • 1,640
  • 10
  • 16
5

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

Does this work for you?

StardustGogeta
  • 3,331
  • 2
  • 18
  • 32
0

You could try using document.getElementById('end-time').valueAsDate which gives you a new Date() with the correct time. From there you can get the hours using .getHours() (0-23) and minutes using .getMinutes() (0-59). See this for more about JavaScript Dates.

ericornelissen
  • 161
  • 2
  • 8
0

Here's a fix for date AND time.

<!DOCTYPE HTML >
<html>
<head>
<title>12 hour Time and Date stamp</title>
<meta name="" content="">
<script>
///////////
///////// DATE generator    /////////
function date_time(id){
        date = new Date;
        year = date.getFullYear();
        month = date.getMonth();
        months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
        d = date.getDate();
        day = date.getDay();
        days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        h = date.getHours();
        if(h<10){h = "0"+h;}
      m = date.getMinutes();
        if(m<10){m = "0"+m;}
       s = date.getSeconds();
        if(s<10){s = "0"+s;}
       result = ''+days[day]+' '+months[month]+' '+d+' '+year;
        document.getElementById(id).innerHTML = result;
        setTimeout('date_time("'+id+'");','1000');
        return true;
}
///////// end DATE Generator /////////
//////////////////////////////////////
/////////// Time Generator ///////////
function tS(){ x=new Date(); x.setTime(x.getTime()); return x; } 
function lZ(x){ return (x>9)?x:'0'+x; } 
function tH(x){ if(x==0){ x=12; } return (x>12)?x-=12:x; } 
function dT(){ if(fr==0){ fr=1; document.write('<font size=3 face=Arial><b><span id="tP">'+eval(oT)+'</span></b></font>'); } document.getElementById('tP').innerHTML=eval(oT); setTimeout('dT()',1000); } 
function aP(x){ return (x>11)?'pm':'am'; } 
var fr=0,oT="' '+tH(tS().getHours())+':'+lZ(tS().getMinutes())+':'+lZ(tS().getSeconds())+' '+aP(tS().getHours())";
///////// end Time Generator /////////
/////////
</script>
</head>

<body>
<!--Date.. Easily adjustable with javascript Array-->
<p><span id="date_time"></span></p>
    <script type="text/javascript">window.onload = date_time('date_time');</script><!--this MUST be included for Date-->
<!--Time in 12 hour format-->
<p><span id="dT"><script language="JavaScript">window.onload = dT('dT');</script></span></p>
</body>
</html> 

I have used this for over 6 years. ALWAYS works. But a couple notes:

1: For the time, adjust the CSS from within the Javascript.
2:Adjust display text (jan,Feb,march... mon,tues,wed,etc...) By changing values within Date Generator Section.

You can see this working at AutoRoXX Network

Hopefully this code snip will help you with what you are trying to accomplish.
I HATE seeing people struggle :-)

James Walker
  • 390
  • 4
  • 19
0

Do not believe accessing .shadowRoot of native <input> elements using DOM methods is currently possible. Where, at chromium, chrome the element

<span 
  role="spinbutton" 
  aria-valuetext="blank" 
  aria-valuemin="1" 
  aria-valuemax="2" 
  aria-help="AM/PM" 
  pseudo="-webkit-datetime-edit-ampm-field">
--
</span>

having .innerHTML of AM or PM is rendered at <input type="time"> element .shadowRoot at change event of element. See Is it possible to access Shadow DOM elements through the parent document?.

Have not found a workaround to select the elements within the .shadowRoot of DOM ` element,

You can use input.valueAsDate.getTime(), which is incremented in values of 3600000, where is value is less than 43200000 the time is "AM", else "PM"; format the output by checking if first two digits of .value is greater than or equal to 13, if true replace first two digits of .value string with value of an object having property names ranging from 13 through 23

var times = {}, re = /^\d+(?=:)/;

for (var i = 13, n = 1; i < 24; i++, n++) {
  times[i] = n < 10 ? "0" + n : n
}

document.getElementById("end-time")
.onchange = function() {
  var time = this
  , value = time.value
  , match = value.match(re)[0];
  this.nextElementSibling.innerHTML =
  (match && match >= 13 ? value.replace(re, times[match]) : value)
  + (time.valueAsDate.getTime() < 43200000 ? " AM" : " PM")
}
<input type="time" name="end-time" id="end-time">
<label for="end-time"></label>
Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177