1

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?

codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167

2 Answers2

2

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

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

Community
  • 1
  • 1
Koen.
  • 25,449
  • 7
  • 83
  • 78