gpt4 book ai didi

javascript - JS : Formatting time and date display on website

转载 作者:行者123 更新时间:2023-12-03 07:31:38 25 4
gpt4 key购买 nike

我有一个在 JavaScript 中打印当前日期和时间的脚本,但是当它打印时间时,缺少一个 0。代码如下:

    var currentdate = new Date();
var datetime = "0" + currentdate.getDate() + ".0"
+ (currentdate.getMonth()+1) + "."
+ currentdate.getFullYear() + "   "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes();
document.write(datetime);

它应该打印 04.03.2016 15:04 并打印 04.03.2016 15:4。

两位数分钟打印正常。

有线索吗?

最佳答案

试试这个

var formatDateDigit = function (i) {
return i <= 9 ? ("0" + i) : i;
};

var currentdate = new Date();

var datetime = formatDateDigit(currentdate.getDate()) + "."
+ formatDateDigit(currentdate.getMonth()+1) + "."
+ currentdate.getFullYear() + " &nbsp; "
+ formatDateDigit(currentdate.getHours()) + ":"
+ formatDateDigit(currentdate.getMinutes());

document.getElementById('my_output_here').innerHTML = datetime;
<div id="my_output_here"></div>

关于javascript - JS : Formatting time and date display on website,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798222/

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