Convert date with offset

Asked

Viewed 23 times

1

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

var d = new Date();
var hora_deslocamento = 2
console.log(d.getHours()+hora_deslocamento);

1 answer

1


You can calculate using Unix Timestamp that makes it very simple, for example:

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));

May also use subtraction.

Explanation of the arithmetic operation:

Number of hours, multiplied by 60 (for minutes), multiplied by 60 (for 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 at the position you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.