0

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)

Jaquelline
  • 13
  • 4
  • By calling `t.setHours` multiple times, you are overwriting what you set before each time. And stuff like `t.setHours(t.getMinutes())` makes little sense to begin with. – 04FS Feb 22 '19 at 09:04
  • So, what is the question? Why `setHours` returns a number? – TiiJ7 Feb 22 '19 at 09:07

2 Answers2

1

If you simply want to know the time 1400 seconds ago, then why not just subtract 1400 seconds from the current time?

var past = new Date((new Date().getTime()) - 1400 * 1000);

getTime() returns the timestamp representing the date/time in milliseconds, hence the multiplication of 1400 by 1000.

phuzi
  • 12,078
  • 3
  • 26
  • 50
0

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);
R3tep
  • 12,512
  • 10
  • 48
  • 75