I have an input that user able to input the time.
I want to get the hours only because I will using it on some of my conditions.
But using the code below, I get NAN value.
Is there a way to get the hour only using <input type="time">
? not included the minutes?
*Example 1:
User input => 10:32 am
get => 10
*Example 2:
User input => 03:11 pm
get => 15 //24hrs.
*Require to use <input type="time">
.
Below is my sample code(attempt only).
function showTime(){
let time = document.getElementById('myTime');
let output = document.getElementById('output');
let getHours = new Date('time').getHours()
console.log(getHours)
getHours < 12 ? output.innerText = 'Morning'
: getHours < 18 ? output.innerText = 'Afternoon'
: getHours < 24 ? output.innerText = 'Evening'
: output.innerText = 'Error getting hour!';
}
span{
border: 1px solid gray;
background-color: gray;
color: darkred;
width: 12rem;
height: 12rem;
}
<label>Time In: </label><input id='myTime' type='time'/>
<br><br>
<button onclick="showTime()">Show Hour Only</button>
<br><br>
<span id='output'></span>
4
Answers
new Date(time)
returns null on which you are trying usegetHours()
. You can split the time value and get the first element of the array using the[0]
index to get the hours.Code Example:
Wrong format, you need year, month and second.
edit line 4 of js to :
and it will work
You should use
time.value
still the input value is only time component not complete date so that you are not able to achieve the required output. Here’s the working code as you wanted.Extracting only hours part from the time and then checking is it valid then outputting it.