我有要求我的项目中的倒数计时器,所以我使用的代码,但该代码显示24小时格式,但我希望12小时格式与AM或PM应显示而不是13,14,15我想要小时应该来像这样 下午1:00,下午2:00,下午3:00。想知道如何做到这一点?
<p id="check_time"></p>
<p id="check_hours"></p>
<script>
var countDownDate = new Date("may 17, 2018 01:37:25").getTime(); //this the which i have to count for difference
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("check_hours").innerHTML = hours;
document.getElementById("check_time").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
答案 0 :(得分:0)
尝试以下方法:
var countDownDate = new Date("june 17, 2018 01:37:25").getTime(); //this the which i have to count for difference
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
var n = new Date();
var h = n.getHours() < 10 ? '0' + n.getHours() : n.getHours();
var min = n.getMinutes() < 10 ? '0' + n.getMinutes() : n.getMinutes();
var sec = h < 10 ? '0' + n.getSeconds() : n.getSeconds();
var time = n.getHours() + ':' + min + ':' + sec;
document.getElementById("check_hours").innerHTML = tConvert(time);
document.getElementById("check_time").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
function tConvert (time) {
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join (''); // return adjusted time or original string
}
&#13;
<p id="check_time"></p>
<p id="check_hours"></p>
<p id="demo"></p>
&#13;