简体   繁体   English

Moment.js - 将 UTC 转换为东部时间

[英]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.我正在使用moment-timezone.js以通过 node.js 将 UTC 时间转换为America/New_York 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.这似乎在我的本地机器上运行良好,但是当我在 AWS Lambda 上运行它时, now时间仍然以 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.我真的不想为了获得准确的纽约时间而使用 API。 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首先,安装时刻时区并使用timezone-with-data.js安装所有时timezone-with-data.js专门只加载您需要的时区

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.如果您知道某个日期采用 UTC moment.utc()并希望将其转换为东部时间,请使用moment.utc()函数实际解析 UTC 日期字符串。 Then when you call .tz() on it will properly convert:然后当你调用.tz()时它会正确转换:

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.如果您只是执行moment(date_string).tz("America/New_York") ,则默认情况下会在本地时区中解析时间,并且不会调整日期。

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.我的主要问题是,无论我在做什么,Amazon Lambda 都以 UTC 时间提供时间。 The fix for this issue was to simply set the Node TZ environment variable:此问题的解决方法是简单地设置 Node TZ 环境变量:

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

Eastern Standard Time (EST) is 5 hours behind Coordinated Universal Time (UTC).东部标准时间 (EST) 比协调世界时 (UTC) 晚 5 小时。

With moment.js, you can subtract 5 hours from UTC timezone.使用 moment.js,您可以从 UTC 时区减去 5 小时。

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 .如果您愿意添加另一个库,例如moment-timezone You can just use:你可以只使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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