Site icon Web Niraj

JavaScript: Using Moment.js to Display Dates & Times in User’s Timezone

The Moment.js library is a great tool to make working with dates and times easier in JavaScript. Not only does it make time / date manipulation easy (unfortunately, it doesn’t support time travel!), it also comes with timezone support. This tutorial shows how you can use Moment.js in your website or application to display dates and times in the user’s local timezone.

Prerequisites

Before you start, you need to make sure you’ve added moment.js and moment-timezone-with-data.js to your website or Cordova application.

Note: It’s recommended to use the minified files to keep your website / application page load times down.

Usage

You can guess the user’s timezone using moment.tz.guess(), which is a good starter for the default timezone to use.

You can then set the default timezone using moment.tz.setDefault(tz), where tz could be from the above guess, or a string like America/Los_Angeles

See the gist on github.

Assuming you are working with UTC times in your application, you can easily convert the UTC time to local time zone using chaining. If you’re not using UTC, you can manually convert from your timezone to the user’s timezone too.

Lines 13 and 17 show how you can convert a given date/time string to a timezone. Line 21 shows how you can convert a date/time string from one timezone to another.

Support

Other examples and a map of supported timezones can be found on the Moment.js Timezone website. Other usage examples are also included on the site.

Feel free to leave a comment below if your specific usage requirements aren’t covered elsewhere.

Exit mobile version