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
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.
Please i need your assistance on how to differentiate between two dates like
(Start Date) 22/04/2017 – 24/04/2018 (End Date) with a result as 12months 2days. Should be done in client side. Any help pls
Showing the different between two dates in number of years, months, etc is a little more complicated than you’d expect with moment. You can achieve this using the following code:
You can remove the years if you only one months and days.
bro how to convert current date and time to other countries date and time
See Line 13 of the example code – it converts UTC to user’s local timezone. You can replace
tz
with any timezone value.