Sometimes, we want to change the 1-24 hour return from the JavaScript date’s getHours
method to a 1-12 hour.
In this article, we’ll look at how to change the 1-24 hour return from the JavaScript date’s getHours
method to a 1-12 hour.
How to change the 1-24 hour return from the JavaScript date’s getHours method to a 1-12 hour?
To change the 1-24 hour return from the JavaScript date’s getHours
method to a 1-12 hour, we can use the %
operator.
For instance, we write:
const hours12 = (date) => {
return (date.getHours() + 24) % 12 || 12;
}
const d = new Date('December 25, 2022 23:15:30')
console.log(hours12(d))
We define the hours12
to return the hours of the date in 12 hour format instead of 24.
In the function, we call date.getHours
to get the hours, which is between 1 and 24.
Then we convert it to 12 hour format by adding 24 and then use the %
to get the remainder when the result is divided by 12.
If the remainder is 0, then we return 12.
Therefore, the console log should log 11.
Conclusion
To change the 1-24 hour return from the JavaScript date’s getHours
method to a 1-12 hour, we can use the %
operator.