How to convert the current local time with specified timezone offset in moment js.?

Viewed 497

I am trying to convert the local time to the other timezone time. So I have used the following code

const timezone = 'UTC-0500';
const dateInput = new Date();
let dateTimeExplicit1 = moment.utc(dateInput).utcOffset(timezone).toDate();

But above code is not giving Local time only, but I am trying to get the EST time. I am not sure how to solve this issue.?

2 Answers

Quick Solution

The problem is toDate() method which does not return the date value converted with offset but the original date.

`let dateTimeExplicit1 = moment.utc(dateInput).utcOffset(timezone).toDate();

If possible, use toString() or toLocaleString() to extract the converted value.

let dateTimeExplicit1 = moment.utc(dateInput).utcOffset(timezone).toString();

Another / Better Solution

I am trying to convert the local time to the other timezone time.

Use moment-timezone.js (plugin to moment.js) to convert the local time to time used in different timezones.

Install plugin:

npm i moment-timezone --save

Example code:

var moment = require('moment-timezone');

const dateInput = new Date();
const timeZone = 'America/New_York';

let dateTimeExplicit1 = moment(dateInput).tz(timeZone).toString();

console.log(dateTimeExplicit1);

One thing to consider: It is not possiblde to use some/many/most of the well known abbreviations (EST, PST etc.) as tz function input value but the documentation tells how developer can modify the data to enable this. See documentation and data in /node_modules/moment-timezone/data/packed/latest.json

Why this is better solution than using offsets? Time is also a political issue and time in certain locations has changed over the years due to changes in regulation. If time conversion is done to historical dates or for example daylight saving times must be taken into account, it is important to know what rules must be applied. Moment timezone features are based on historical and current timezone data maintained by IANA.

You can use this solution with dayjs (Fast 2kB alternative to Moment.js):

import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';

dayjs.extend(timezone);
dayjs.extend(utc);

console.log(dayjs.utc(new Date()));


with moment you can use this method:

console.log(moment().utcOffset(new Date().toDateString()));

Related