jQuery - Change 1-24 hour to 1-12 hour using .getHours() method?

只谈情不闲聊 提交于 2019-12-02 08:22:09

You can achieve this using the modulus % operator, which finds the remainder of a division operation.

For example, 11 % 12 and 23 % 12 both equal 11, like a 12-hour clock would portray.

var hours = new Date().getHours() % 12;
if (hours == 0) {
    hours += 12;
}

http://jsfiddle.net/ph7Vf/

Try with this:

hours = (hours < 12 ? hours : hours - 12).toString().replace(/^\d{1}$/, '0$&');

Edit: It could be shorter, based on Vulcan's answer:

hours = (hours % 12).toString().replace(/^\d{1}$/, '0$&');
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!