Search code examples
javascriptdatetimeclockseconds

javascript : Error for increment 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>

I want to auto increment the seconds. I know that if I am using

var today = new Date();

Instead of this,

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

it will be executed successfully.but i don't want that.I need the output based on the code written above.

Thanks


Solution

  • Try this modification for 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);
    }
    

    Example - https://jsfiddle.net/1btotz3a/