0

我的意思是有两个时钟,一个是 24 小时制的,另一个是 12 小时制的,

function updateClock() {
    var currentTime = new Date();
    var currentHoursAP = currentTime.getHours();
    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();

    // Pad the minutes and seconds with leading zeros, if required
    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
    currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;

    // Choose either "AM" or "PM" as appropriate
    var timeOfDay = (currentHours < 12) ? "AM" : "PM";

    // Convert the hours component to 12-hour format if needed
    currentHoursAP = (currentHours > 12) ? currentHours - 12 : currentHours;

    // Convert an hours component of "0" to "12"
    currentHoursAP = (currentHours == 0) ? 12 : currentHours;

    // Compose the string for display
    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + " / " + currentHoursAP + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

    $("#clock").html(currentTimeString);
}

$(document).ready(function () {
    setInterval(updateClock, 1000);
});

但最终达到currentHourscurrentHoursAP成为完全相同的值。
我错过了什么?

4

2 回答 2

2

问题是

// Convert an hours component of "0" to "12"
currentHoursAP = (currentHoursAP == 0) ? 12 : currentHoursAP;

如果currentHoursAP != 0 然后不是设置currentHoursAP您的值,而是将其设置回currentHours

演示:小提琴

于 2013-08-06T03:15:19.830 回答
1

getHours是从零开始的 ( 0 = 12 AM, 23 = 11 PM),因此您需要调整检查:

currentHoursAP = (currentHours >= 12) ? currentHours - 12 : currentHours;
currentHoursAP = (currentHoursAP == 0) ? 12 : currentHoursAP;
于 2013-08-06T03:16:31.697 回答