MomentJS Timezone based on location

Viewed 374

If I were to use momentJS in my VPS server, does it create a date + time based on the location of where the server is located?

For Eg:

If my server is somewhere in Country A and the client access the site in Country B, does momentJS create time based on Country A or B?

Hope this question makes sense..

1 Answers

Moment.js will normally use the configured time and timezone on the machine that runs the code.

However you can also create a moment instance set to UTC time, and you can also get time in any timezone using Moment Timezone, e.g. America/Los_Angeles etc.

I would suggest using UTC time in a server context to be consistent for events. This way you don't get caught by issues if you change the server location. All events are recorded in UTC and clients can convert to their local time as required.

// Local time (of machine running code e.g. server)
console.log('Local time:', moment().format());

// UTC time
console.log('UTC time :', moment.utc().format());

const timezones = ['America/Los_Angeles', 'Europe/Paris'];
console.log('Time in timezones:');
for(let tz of timezones) {
    console.log(`Time in timezone ${tz}:`, moment.tz(tz).format());
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

<script src="https://momentjs.com/downloads/moment-timezone-with-data-1970-2030.js"></script>

Related