简体   繁体   中英

Moment.js - Converting UTC To Eastern Time

I am using moment-timezone.js in order to convert UTC time to America/New_York via node.js. I am doing this like so:

var moment  = require('moment-timezone');
moment.tz.add('America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0');

var now    = new Date().toISOString();
now = moment(now).tz("America/New_York").toDate();

This seems to work fine on my local machine, but when I run it on AWS Lambda, the now time is still being outputted as UTC.

Am I doing something wrong here? I really don't want to have to use an API just to get the accurate New York time. Daylight savings is the biggest challenge here. Thanks!

First, install moment timezone and install all of the timezones by using timezone-with-data.js or specifically only load the timezones you need

If you have a date that you know is in UTC and want to convert it to Eastern time, use the moment.utc() function to actually parse the UTC datestring. Then when you call .tz() on it will properly convert:

moment.utc(date_string).tz("America/New_York")

If you simply do moment(date_string).tz("America/New_York") the time gets parsed in your local timezone by default, and it will not adjust the date.

The way I figured this out was to do:

var now = ((moment(Date.now()).utcOffset('-0500').format('x'));
//Parse it into native JS object: 
now = new Date(parseInt(now));

I want to point something out though that I hope will save someone the days of time this burdened me for. My main issue was that Amazon Lambda was providing time in UTC, no matter what I was doing. The fix for this issue was to simply set the Node TZ environment variable:

process.env.TZ = 'America/New_York';

Eastern Standard Time (EST) is 5 hours behind Coordinated Universal Time (UTC).

With moment.js, you can subtract 5 hours from UTC timezone.

moment.utc().subtract(5, 'hours').format("YYYY-MM-DD HH:mm:ss.SSS")

Or

If you are willing to add another library like moment-timezone . You can just use:

moment().tz("America/New_York").format("YYYY-MM-DD HH:mm:ss.SSS")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM