Home > Enterprise >  change the time zone from local to server time
change the time zone from local to server time

Time:12-17

I have a problem with the time of my app in the heat map area. The time must be taken from the server zone and not from the time of each device from which a user connects. I live in a country with a -5 time zone and I have to manually subtract -5 from the hour. I would like the app to set the UTC server time.

const dateLimit = moment(new Date().toJSON(), 'YYYY-MM-DD HH:mm:ss').subtract(5, 'hours').format('YYYY-MM-DD HH:mm:ss')

    

CodePudding user response:

You can use UTC time. This will make the time consistent across all devices. To set the dateLimit variable to the current UTC time rather than the device's time zone, you can use the moment.utc() function as follows:

const dateLimit = moment.utc(new Date().toJSON(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')

CodePudding user response:

If you have a server that returns time here is how you do it

async function getServerTime() {
  const response = await fetch('http://example.com/time');
  const time = await response.text();
  return time;
}

const dateLimit = moment(await getServerTime(), 'YYYY-MM-DD HH:mm:ss').subtract(5, 'hours').format('YYYY-MM-DD HH:mm:ss')

This code sends a request to the server at the URL http://example.com/time, which should return the current time in the desired format. The getServerTime function returns a promise that resolves to the time string returned by the server. The dateLimit variable is then created by parsing the time string using the moment library and subtracting 5 hours from it.

Keep in mind that this code assumes that the server is providing the time in the format 'YYYY-MM-DD HH:mm:ss'. If the server returns the time in a different format, you will need to adjust the code accordingly.

  • Related