Search code examples
javascriptmillisecondsgettime

setHours() javascript returns a diffrent format then expected


I have this situation where I am in need of using the JavaScript

setTime()

So that I can modify the time, according to a number of seconds I have. For example I want to know what time it was 1400 sec ago.

I come to the conclusion that my cleanest and best solution it would be to use a combination of

getDate() and setHours() - setMinutes() - setSeconds() like in the example in this link: https://codepen.io/Jaquelline/pen/rPgOKj?editors=1011

function myFunction() {
var myTime = new Array();
    for(i=0; i <3599; i++){
     var d = new Date();
     var currentI = 3599-i;
        myTime[i] = new Array();
        myTime[i] = {
          x: i,
          y: d.setHours(d.getHours()-1) + ':' + d.setMinutes(d.getMinutes()) + ':'+ d.setSeconds(d.getSeconds()+currentI)
        };
    }

var s = JSON.stringify(myTime);
document.getElementById("cTimeArray").innerHTML =s;


 var t = new Date();
 t.setHours(t.getHours()-1);
 t.setHours(t.getMinutes());
 t.setHours(t.getSeconds()+1200);
 document.getElementById("cTime").innerHTML =t;
}

The s variable returns something like this:

[{"x":0,"y":"1550821508351:1550821508351:1550825107351"}, {"x":1,"y":"1550821508351:1550821508351:1550825106351"},

While t returns :

Sun Apr 14 2019 08:45:08 GMT+0200 (Mitteleuropäische Sommerzeit)


Solution

  • You don't show the correct value.

    Set d before and use the getters to show the value.

    var myTime = new Array();
    
    for (i = 0; i < 3599; i++) {
      var d = new Date();
      var currentI = 3599 - i;
      myTime[i] = {};
    
      d.setHours(d.getHours() - 1);
      d.setMinutes(d.getMinutes());
      d.setSeconds(d.getSeconds() + currentI);
      myTime[i] = {
        x: i,
        y: d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
      };
    }
    
    var s = JSON.stringify(myTime);
    console.log(s);