javascript - jQuery时钟12/24小时在一起

标签 javascript jquery

我打算有两个时钟,一个是 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 变成完全相同的值。
我错过了什么?

最佳答案

问题是

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

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

演示:Fiddle

关于javascript - jQuery时钟12/24小时在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18071236/

相关文章:

jQueryMobile : how to work with slider events?

javascript - 使用javascript函数调用模拟post表单提交

jquery - 如何将选择框与 jQuery AutoComplete 一起使用?

javascript - 在服务 worker 中缓存 webpack 哈希 url

javascript - 防止 $watchCollection 在 init 时触发

javascript - Electron 锻造制造不会建立

javascript - 无限自动滚动动态内容,例如附加

javascript - 使用 jQuery 获取完整的 URL,包括问号后的参数?

javascript - $(class).click() 不起作用

javascript - 如何比较数组中的元素 (javascript)