Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock the browser's timezone? [duplicate]

I want to test a location feature in a web site, to make this test I need to try different time-zones. I obtain the timezone with a javascript code, calling the following function:

var offset = new Date().getTimezoneOffset();

Now this function returns to me 180 because I am in Argentina, I need to test with different time-zones. Somebody knows how to do this? Many thanks!!

like image 879
McSas Avatar asked Aug 31 '12 18:08

McSas


People also ask

How do I simulate different time zones in my browser?

Method 1: Using Developer Tools to Change Chrome TimezoneOpen DevTools in Chrome -> Open the Console drawer. Click on the three-dotted menu -> Click on More tools -> Sensors. From the Sensors tab, set the location according to your preference and define the specific timezone.

How do I get timezone offset on my browser?

To get the current browser's time zone, you can use the getTimezoneOffset() method from the JavaScript Date object. The getTimezoneOffset() returns the time difference, in minutes, between UTC time and local time.


1 Answers

The accepted answer doesn't really mock the Date.getTimezoneOffset method, instead it expects you to use a different method with the same name.

It won't work on Date objects themselves and as Carl Meyer points out, it won't work for libraries like MomentJS.

A better way is to override the getTimezoneOffset method on the Date prototype, so that all instances of Date have the overridden method.

d = new Date(); // Mon Jul 13 2015 10:58:12 GMT+0200 (CEST)
alert(d.getTimezoneOffset()); // -120, My local "real" timezone.

// Save the original method.
var getTimezoneOffset = Date.prototype.getTimezoneOffset;

Date.prototype.getTimezoneOffset = function () {
    return 160;
}
// Now Date objects will have the mocked timezone offset
alert(d.getTimezoneOffset()); // 160, The mocked timezone.

// Now restore the method to its original version
Date.prototype.getTimezoneOffset = getTimezoneOffset;
alert(d.getTimezoneOffset()); // -120
like image 134
JC Brand Avatar answered Sep 21 '22 14:09

JC Brand