how to remove getTimezoneOffset

Question

I know that Date object is using machine timezone (where the code is running). I have a specific use case that I need to clear the offset.

var d = new Date();
console.log(d.getTimezoneOffset())

This print the offset from the UTC. I'd like to force the offset to be zero and I did this

var getTimezoneOffset = Date.prototype.getTimezoneOffset;
Date.prototype.getTimezoneOffset = function removeTimezoneOffset() {
    return 0;
  };

and I reset after I did something

Date.prototype.getTimezoneOffset = getTimezoneOffset

This will fail in eslint complaining Date prototype is read only, properties should not be added. Is there any better way to remove the time offset?


Show source
| javascript   | date   | timezone   2017-03-16 23:03 2 Answers

Answers to how to remove getTimezoneOffset ( 2 )

  1. 2017-03-16 23:03

    You probably want date.toISOString(), or otherwise check this question; How do you convert a JavaScript date to UTC?

  2. 2017-03-16 23:03

    I get the feeling that you're using some other code that uses getTimezoneOffset and rather that modify that code, you're changing the method.

    Without knowing the specific issue, you could also just modify the date by the local time zone offset so that "local" methods return UTC values:

    function formatAsISO(d){
      function z(n){return (n<10?'0':'')+n}
      return d.getFullYear() + '-' + z(d.getMonth()+1) + '-' +
             z(d.getDate()) + ' ' + z(d.getHours()) + ':' +
             z(d.getMinutes()) + ':' + z(d.getSeconds());
    }
    
    var d = new Date();
    
    // Local date
    console.log('Local   : ' + formatAsISO(d));
    
    // UTC equivalent
    console.log('UTC     : ' + d.toISOString());
    
    // Adjust so local looks like UTC
    d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
    console.log('Adjusted: ' + formatAsISO(d));

    Which modifies the actual date, so you might need to pass a copy of it to the (unspecified) function.

Leave a reply to - how to remove getTimezoneOffset

◀ Go back