0

Hey there i have the following problem. I am sure you could help me:

I have a button that change the hour +1 hour or - 1 hour. But the date jumps from 00UTC to 23 UTC on the same day and not the day before.

Note: addZero completes the string from 1 to "01" (it is because an image string needs 01 02 03 )

function switch_image(i) {
  if (i == 0) {
    d.setUTCHours(d.getUTCHours() - 1);

    if (d.getUTCHours() == 23) {
      d.setUTCDate(d.getUTCDate() - 1);
    }
    h = addZero(d.getUTCHours());

  } else {
    d.setUTCHours(d.getUTCHours() + 1);

    if (d.getUTCHours() == 0) {
      d.setUTCDate(d.getUTCDate() + 1);
    }
    h = addZero(d.getUTCHours());
  }
} 

Thanks a lot for your help ;)

dl.meteo
  • 1,658
  • 15
  • 25
  • possible duplicate of [Adding hours to Javascript Date object?](http://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object) – Ding Feb 05 '15 at 16:44

2 Answers2

0

I found the solution by myself. I forgot to set the variable for days (it s t, for hpurs its h) new. Best regards .

dl.meteo
  • 1,658
  • 15
  • 25
0

See the following function which adds a constant value to another date using Date.UTC(1970,0,1) as a starting value (Jan 1, 1970 is the Unix epoch). Note that months and years aren't included because they aren't constant times (there are leap years and months don't span the same number of days).

Date.prototype.addTime = function(days,hours,minutes,seconds,milliseconds){
  for(var i=0;i<arguments.length;i++){
    arguments[i]=parseInt(arguments[i]);
  }
  return new Date(this.getTime() +
      Date.UTC(1970, 0,
          (isNaN(days) ? 0 : days) + 1,
          isNaN(hours) ? 0 : hours,
          isNaN(minutes) ? 0 : minutes,
          isNaN(seconds) ? 0 : seconds,
          isNaN(milliseconds) ? 0 : milliseconds));
}
document.body.innerHTML = new Date(Date.now()).addTime(1,1).toString(); //Adds 1 day,1 hour

Reference: MDN

Pluto
  • 2,900
  • 27
  • 38