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

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


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 offsetalert(d.getTimezoneOffset()); // 160, The mocked timezone.// Now restore the method to its original versionDate.prototype.getTimezoneOffset = getTimezoneOffset;alert(d.getTimezoneOffset()); // -120


You could use a function for this.

function getTimezoneOffset() {  if (DEBUG) {    return 600; // for Australian Eastern Standard Time  }  return new Date().getTimezoneOffset();}

Where DEBUG is a variable set earlier on to determine whether you're testing or not.

Then use that function throughout your code, instead of the method on the Date object.