gpt4 book ai didi

javascript - 如何使用 javascript 以 12 小时格式显示早安/下午/晚上

转载 作者:行者123 更新时间:2023-11-28 14:35:16 26 4
gpt4 key购买 nike

现在是下午 4:11,但我的输出显示为“早上好” - 为什么会发生这种情况?

$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var h = ndate.getHours() % 12;
var format = h >= 12 ? 'PM' : 'AM';
var m = ndate.getMinutes().toString();
var s = ndate.getSeconds().toString();

if (h < 12) {
h = "0" + h;
$("h3.day-message").html("Good Morning");
} else if (h < 18) {
$("h3.day-message").html("Good Afternoon");
} else {
$("h3.day-message").html("Good Evening");
}

if (s < 10) {
s = "0" + s;
}

if (m < 10) {
m = "0" + m;
}

$('.date').html(h + ":" + m + ":" + s + format);
}

setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>

最佳答案

问题是因为您使用的是模运算符。这意味着您的 h > 12检查永远不会被命中,因为除法的余数不能大于 12 。正因为如此,你的逻辑总是相信现在还是早上。要解决此问题,只需使用简单的 <比较小时数字时进行检查。

另请注意,您在日期格式方面存在一些问题,例如附加额外的零,因此最终会得到 011作为小时值。您可以使用 slice() 来修复此问题.

话虽如此,试试这个:

$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var hours = ndate.getHours();
var message = hours < 12 ? 'Good Morning' : hours < 18 ? 'Good Afternoon' : 'Good Evening';
$("h3.day-message").text(message);

$('.date').html(hours.leadingZeroes(2) + ":" + ndate.getMinutes().leadingZeroes(2) + ":" + ndate.getSeconds().leadingZeroes(2) + (hours < 12 ? 'AM' : 'PM'));
}

setInterval(dateTime, 1000);
});

Number.prototype.leadingZeroes = function(len) {
return (new Array(len).fill('0', 0).join('') + this).slice(-Math.abs(len));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>

关于javascript - 如何使用 javascript 以 12 小时格式显示早安/下午/晚上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49996649/

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