Monkey patching JS Date to force UTC

64 Views Asked by At

Everything in our app uses UTC and we want to display it as-is, e.g. 2023-10-10T00:00:00Z from the server is always midnight, it's not 02:00 of 10. October in Prague, it's not 8PM of October 9 in New York, it's just midnight without timezone. No DST, no leap seconds, nothing local. End of day, 3 hours afterwards, ... everything in UTC.

We use https://docs.dhtmlx.com/gantt/ (which needs native Date) and will be migrating from Ant Design v4 (moment) to v5 (dayjs or date-fns).

Our existing code is a mess of adding and subtracting .getTimezoneOffset() for native Dates in some files while using moment.utc() in other files.

I am playing with the idea to just monkey-patch the Date object to solve this "once and for all":

/* eslint-disable no-extend-native, @typescript-eslint/no-unsafe-assignment */
Date.prototype.getTimezoneOffset = () => 0
Object.getOwnPropertyNames(Date.prototype).filter((method) => method.match(/UTC/)).forEach(method => {
  // @ts-expect-error
  Date.prototype[method.replace('UTC', '')] = Date.prototype[method]
}) 
/* eslint-enable */

I would like to ask What can possibly go wrong?, but for real:

  • What potential bugs should I expect?
  • What npm libs do we have to put on a "do not use" list? (or rather, what are the steps to evaluate a lib?)
0

There are 0 best solutions below