Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda