gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:22:15 25 4
gpt4 key购买 nike

我打算有两个时钟,一个是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com