JS:格式化网站上的时间和日期

时间:2016-03-04 14:13:39

标签: javascript date time

我有一个用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。

两位数分钟打印正常。

任何线索?

1 个答案:

答案 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() + " &nbsp; "
  + formatDateDigit(currentdate.getHours()) + ":"
  + formatDateDigit(currentdate.getMinutes());

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