This function converts time to 12hr format, credits to a contributor on Stack Overflow for this function:
JS
function ampm(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // 0 should be 12
minutes = minutes < 10 ? '0'+minutes : minutes; // if minutes less than 10, add a 0 in front of it ie: 6:6 -> 6:06
var strTime = hours + ':' + minutes + ' ' + ampm;
document.getElementById('time').value = strTime;
return strTime;
}
////This is how the value of the time input is supposed to be displayed in 12 hr format
_("display_time").innerHTML = ampm(new Date());
HTML
<!--This is the input field where a user selects a time-->
<input id="time" placeholder="Time" type="time" name="time" />
<!--This is where the value of the time input is supposed to be displayed in 12 hr format-->>
<span id="display_time"></span>
My question is how do I get the value of the time input field to be displayed on the span tag in 12hr format. This code is semi-working.
It displays the time in 12hr format but only displays the current time. The flow chart would be something like, user selects time in time input -> some JS to convert to 12hr format -> display as 12hr format in span tag. Any advice or suggestions?
Your input value will be a string, not a date. I've set up a jsfiddle where I've modified your javascript to work on a string.
$('#time').on('change', function() {
var date = $('#time').val().split(':');
var hours = date[0];
var minutes = date[1];
$('#display_time').text(ampm(hours, minutes));
});
function ampm(hours, minutes) {
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12 || 12;
minutes = minutes || 0;
minutes = minutes < 10 ? '0'+minutes : minutes;
return hours + ':' + minutes + ' ' + ampm;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With