![]() |
Moment.js is a powerful library for working with dates and times in JavaScript. One common requirement is to convert a date and time from Coordinated Universal Time (UTC) to the local time zone of the user’s device. This is especially useful for applications that need to display times in the user’s local context. To use the MomentJS library, we must ensure that we have installed the library. We can do so by using the following command. Installing Moment.js in Node.jsnpm i moment These are the following approaches: Table of Content Using the local() methodIn this approach, we are using the local() method of Moment.js. This method converts the date and time from UTC to the local time zone. This method is simple and straightforward. Syntax:moment.utc().local(); Example: Below example uses a local() method in momentJS to convert from UTC to local time.
Output: Local time for 2024-07-26T12:00:00Z (UTC) is: 2024-07-26 17:30:00 Using the utcOffset() MethodIn this approach we are using the utcOffset() method which allows us to set a specific UTC offset to convert the time. This method is useful if we need to convert the time to a different time zone, not just the local one. Syntax:moment.utc().utcOffset(offset); Example: Below example uses utcOffset() method in momentJS to convert from UTC to local time.
Output: Time for 2024-07-26T12:00:00Z (UTC) with offset -240 is: 2024-07-26 08:00:00 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 24 |