Convert date with offset

1

I want to do a time offset, ie add or subtract the time. The problem is if the time is 24, and shift 1, the final time will be 25. The same case for if the time is 0, and shift -1, the result will be -1. How can I resolve this?

var d = new Date();
var hora_deslocamento = 2
console.log(d.getHours()+hora_deslocamento);
    
asked by anonymous 17.04.2015 / 00:34

1 answer

1

You can calculate using Unix Timestamp which makes it very simple, eg:

function horasDeslocamento(date, horas){
    return new Date(date.getTime() + (horas * 60 * 60 * 1e3));
}

Now you can use it as follows:

var d = new Date();
console.log(horasDeslocalmento(d, +2));

You can also use subtraction.

Explanation of the arithmetic operation:

Number of hours, multiplied by 60 (referring to minutes), multiplied by 60 (referring to seconds), multiplied by 10 to 3 (1000) for milliseconds.

The result of this operation is added to the UNIX Timestamp value of your date object and returns a new initialized object in the position you want.

    
17.04.2015 / 03:16