javascript 使用 moment.js 将 Utc 日期更改为本地日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19401426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing the Utc Date to Local Date using moment.js
提问by Anto Subash
i'm using moment.js with timezones for date manipulation in a webapp. i'm storing all the dates in UTC and return them to UI as UTC. I'm having the timezone of the user. i want to convert the UTC time to the local Users time zone.
我正在使用带有时区的 moment.js 在 webapp 中进行日期操作。我将所有日期存储在 UTC 中,并将它们作为 UTC 返回到 UI。我有用户的时区。我想将 UTC 时间转换为本地用户时区。
var timezone = "America/New_York";
var utcDate = "2013-10-16T10:31:59.0537721Z";
var localDate = moment(utcDate).utc().tz(timezone).format()
When i try to do this i'm getting wrong time. not sure how to get this working with moment
当我尝试这样做时,我的时间错了。不知道如何让这个工作与时刻
采纳答案by Matt Johnson-Pint
You can try:
你可以试试:
moment.utc(utcDate).tz(timezone).format()
But it shouldn't matter. They should both produce: "2013-10-16T06:31:59-04:00"
.
但应该没关系。他们都应该产生: "2013-10-16T06:31:59-04:00"
。
It works for me, running on Chrome 30, so it's probably browser related.
它对我有用,在 Chrome 30 上运行,所以它可能与浏览器有关。
If you're running Moment.js 2.3.1 or earlier on IE8, then it's a side effect of issue #1175, which was fixed in 2.4.0. Updating to the latest version should solve the problem.
如果您在 IE8 上运行 Moment.js 2.3.1 或更早版本,那么这是问题#1175 的副作用,该问题已在 2.4.0 中修复。更新到最新版本应该可以解决问题。
回答by bguiz
Use the +
operator to get unix time, then:
使用+
运算符获取 unix 时间,然后:
moment(+moment.utc(utcDate))
How it works:
怎么运行的:
moment.utc(String)
parses the string and returns a moment object set to UTC timezone.+
returns the unix offset in milliseconds for the moment obejctmoment(Number)
creates a new moment object in the user's local time zone, using the passed in unix offset.
moment.utc(String)
解析字符串并返回一个设置为 UTC 时区的时刻对象。+
返回当前对象的 unix 偏移量(以毫秒为单位)moment(Number)
使用传入的 unix 偏移量在用户的本地时区创建一个新的时刻对象。
回答by ktutnik
for anyone having the same problem:
对于任何有同样问题的人:
your date iso format should contain the timezone. here is the format allowed by momentjs:
您的日期 ISO 格式应包含时区。这是momentjs允许的格式:
YYYY-MMM-DDTHH:mm:ss+00:00
notice the +00:00 mean it is UTC
注意 +00:00 表示它是 UTC
example
例子
moment('2014-10-03T09:31:18+00:00').format()
will terturn
会转
"2014-10-03T17:31:18+08:00"