Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add or subtract timezone difference to javascript Date

What is the best approach to add or subtract timezone differences to the targetTime variable below. The GMT timezone values comes from the DB in this format: 1.00 for London time, -8.00 for Pacific time and so on.

Code looks like this:

date = "September 21, 2011 00:00:00"; targetTime = new Date(date); 
like image 931
halliewuud Avatar asked Sep 13 '11 14:09

halliewuud


People also ask

How do you subtract time in JavaScript?

To subtract hours from a date:Use the getHours() method to get the hours of the specific date. Use the setHours() method to set the hours for the date. The setHours method takes the hours as a parameter and sets the value for the date.

Can you subtract dates in JavaScript?

Subtract dates using getTime() method And that's how you can subtract dates in JavaScript.


1 Answers

You can use Date.getTimezoneOffset which returns the local offset from GMT in minutes. Note that it returns the value with the opposite sign you might expect. So GMT-5 is 300 and GMT+1 is -60.

var date = "September 21, 2011 00:00:00"; var targetTime = new Date(date); var timeZoneFromDB = -7.00; //time zone value from database //get the timezone offset from local time in minutes var tzDifference = timeZoneFromDB * 60 + targetTime.getTimezoneOffset(); //convert the offset to milliseconds, add to targetTime, and make a new Date var offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000); 
like image 87
alexp Avatar answered Sep 21 '22 02:09

alexp