How do I pass the value of an input type time to a Date object?

18,690

Solution 1

There's no need to use Date and its methods the input is a String so you better use .split(":") method and you will get the hours and minutes values directly.

Then just test if their values are lower than 10 add a leading 0 and if the hours is higher than 12 use pm suffix or use am otherwise.

This is a live DEMO using onchange event of the time input with its value as parameter onchange="ampm(this.value) :

function ampm(time) {

  console.log(time);
  if (time.value !== "") {
    var hours = time.split(":")[0];
    var minutes = time.split(":")[1];
    var suffix = hours >= 12 ? "pm" : "am";
    hours = hours % 12 || 12;
    hours = hours < 10 ? "0" + hours : hours;

    var displayTime = hours + ":" + minutes + " " + suffix;
    document.getElementById("display_time").innerHTML = displayTime;
  }
}
<!--This is the input field where a user selects a time-->
<input id="time" placeholder="Time" type="time" name="time" onchange="ampm(this.value)" />
<span id="display_time"></span>

Solution 2

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;
}

Solution 3

Something like this will do it

function showTime() {
    //Grab the time and split into hrs and mins
    var time = document.getElementById("time");
    if ( time.value === "")  {
        document.getElementById("mySpan").innerHTML = "";
        return false;
    }
    var hrs = time.value.split(":")[0];
    var mins = time.value.split(":")[1];
    var newTime = ampm(hrs, mins);
    document.getElementById("mySpan").innerHTML = newTime;
}

function ampm(hrs, mins) {
    return ( hrs % 12 || 12 ) + ":" + mins + (( hrs >= 12 ) ? "PM" : "AM" );
}

Here is a an example. showTime() just needs to be ran onchange of the time input.

Share:
18,690
Arvin Flores
Author by

Arvin Flores

Updated on June 05, 2022

Comments

  • Arvin Flores
    Arvin Flores almost 2 years

    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?

  • Mark Walters
    Mark Walters over 8 years
    @RobG That would work except you still need a separate statement for 12 as when it's greater than 12 we need to remove 12 to represent a 12 hour clock
  • Mark Walters
    Mark Walters over 8 years
    @RobG I've made an edit. It is a little more elegant, thanks
  • RobG
    RobG over 8 years
    (function(h,m){return(h%12||12)+':'+m+(h<12?'am':'pm')}.appl‌​y([],'13:08'.split('‌​:')))
  • Arvin Flores
    Arvin Flores over 8 years
    What does the '0' mean in var hours = time.split(":")[0] ? Same with the '1' in var minutes?
  • cнŝdk
    cнŝdk over 8 years
    @ArvinFlores these are indexes, because split gives an array as result so with [0] we get the first element and [1] we get the second one.
  • Arvin Flores
    Arvin Flores over 8 years
    Ok. In var suffix, shouldnt it be >= 12 instead of just >12? Since itll go from 11:59 am to 12:00am instead of 12:00 pm?