Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Manipulate JS Date internal time

I am trying to sync my client app time to my server time (it matters because the app is serverless and has offline-work). On the app startup I calculate the time difference and then override the Date.now() method to add the difference into original now. For example assume this code:

Date.__serverDifference = calculateServerDifference();
Date.__now = Date.now;
Date.now = () => Date.__now() + Date.__serverDifference;

and it works fine. But the problem is about other Date functionalities. For example if I use new Date() it will return original time and it doesn't care the overridden now method.
As the MDN documentation says:

JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.

Is there any way to override the js Date Class to return all current times according to this new calculation?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The best approach would be to create helper methods that include the offset for all functions for which the built-in functions don't return the desired value. Your Date.__now is a start, but you could also have:

const offset = calculateServerDifference();
const newDateIncludingOffset = (...args) => {
  const date = new Date(...args);
  date.setMilliseconds(date.getMilliseconds() + offset);
  return date;
};

And then replace all instances of new Date(...args) with newDateIncludingOffset(...args). If you have a lot of references to new Date already - bite the bullet and change them appropriately.

While you could change methods on the prototype, that's not such a good idea - using your own functions and methods while not changing the built-ins is a much better approach.

You could also replace window.Date entirely with something new, with your own methods, allowing you to change the Date constructor to factor in the offset you need - but again, that's not a great idea and can lead to fragile code and incompatibility issues.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!