javascriptreact-nativemomentjsmoment-timezone

Using a Global Initial Date with Moment.js in a React Native Application


In our React Native application, we're using moment.js for various date and time manipulations. However, we need to set a global initial date and time, which should be used throughout the entire application for all moment.js operations.

Problem: The main issue is how to set this global initial date and time so that any subsequent moment.js operations will use it as their base. Additionally, this initial date and time could be updated in one part of the application and should reflect immediately in all other parts.

I write the code like this but the time never increases. Does it remain constant?

export const setDefaultTime = (date: string, time: string) => {
  const serverDate = `${date} ${time}`;

  const serverMoment = moment.utc(serverDate);

  moment.now = function () {
    return serverMoment.valueOf();
  };
};

Then I use moment.now() on another page. It gives me the date and time, but the date and time never increase.


Solution

  • I can set the default date and time with this logic.

    export const setDefaultTime = (date: string, time: string) => {
      const serverOffset = moment(`${date} ${time}`).diff(new Date());
    
      moment().add(serverOffset, 'milliseconds');
    
      moment.now = () => {
        return new Date().getTime() + serverOffset;
      };
    };