javascript:增量秒的错误

时间:2017-01-19 15:07:13

标签: javascript date time clock seconds

<html>
<head>
<script>
function startTime() {
    var st = "January 19, 2017 18:33:31" 
    var today = new Date(st);
    var montharray = new Array("Jan","Feb","Mar","Abr","May","Jun","Jul","Ogu","Sep","Oct","Nov","Des");
    var h = today.getHours();
    var ampm = h >= 12 ? 'PM' : 'AM';
    h = h % 12;
    h = h ? h : 12;
    var m = today.getMinutes();
    var s = today.getSeconds();
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    checkTime(today.getDate())+" "+montharray[today.getMonth()]+" "+today.getFullYear() + " (" + ampm +" " + h + ":" + m + ":" + s +")"; 
    setTimeout(startTime, 1000);
}

function checkTime(i) {
    if (i < 10) {i = "0" + i};
    return i;
}
</script>
</head>
<body onLoad="startTime();">
    <span id="txt"></span>
</body>
</html>

我想自动增加秒数。 我知道如果我正在使用

var today = new Date();

而不是这个,

var st = "January 19, 2017 18:33:31" 
        var today = new Date(st);

它会成功执行。但我不想要那个。我需要的  输出基于上面编写的代码。

由于

1 个答案:

答案 0 :(得分:1)

尝试对startTime进行此修改

var st = "January 19, 2017 18:33:31";
function startTime() {
    var today = new Date(st);
    var montharray = new Array("Jan","Feb","Mar","Abr","May","Jun","Jul","Ogu","Sep","Oct","Nov","Des");
    var h = today.getHours();
    var ampm = h >= 12 ? 'PM' : 'AM';
    h = h % 12;
    h = h ? h : 12;
    var m = today.getMinutes();
    var s = today.getSeconds();
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    checkTime(today.getDate())+" "+montharray[today.getMonth()]+" "+today.getFullYear() + " (" + ampm +" " + h + ":" + m + ":" + s +")"; 
    today.setSeconds(today.getSeconds() + 1);
    st = today;
    setTimeout(startTime, 1000);
}

示例 - https://jsfiddle.net/1btotz3a/