我有一个用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。
两位数分钟打印正常。
任何线索?
答案 0 :(得分:1)
试试这个
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() + " "
+ formatDateDigit(currentdate.getHours()) + ":"
+ formatDateDigit(currentdate.getMinutes());
document.getElementById('my_output_here').innerHTML = datetime;
<div id="my_output_here"></div>