jQuery - Change 1-24 hour to 1-12 hour using .getH

2019-03-06 14:58发布

Fiddle: http://jsfiddle.net/bnsex/1/

I want to use 12 hour clock for this code...

$(document).ready(function() {

setInterval( function() {
var hours = new Date().getHours();
$(".hours, .hour").html(( hours < 10 ? "0" : "" ) + hours);
}, 1000);

}); ​

Your help is much appreciated :D

标签: jquery time hour
2条回答
我命由我不由天
2楼-- · 2019-03-06 15:19

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/

查看更多
等我变得足够好
3楼-- · 2019-03-06 15:19

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$&');
查看更多
登录 后发表回答