javascript Moment.js 和 Unix Epoch 转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18022534/
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
Moment.js and Unix Epoch Conversion
提问by Robert Kaucher
I have a web service that is returning a date as the following string:
我有一个 Web 服务,它返回一个日期为以下字符串:
/Date(1377907200000)/
/Date(1377907200000)/
I use MomentJS to parse this to a moment
object.
我使用 MomentJS 将其解析为一个moment
对象。
moment("/Date(1377907200000)/")
=> Fri Aug 30 2013 20:00:00 GMT-0400
moment("/Date(1377907200000)/")
=> Fri Aug 30 2013 20:00:00 GMT-0400
All of that is fine. But when I call unix()
on the object I am given the value 1377907200
. This, however, corresponds to Fri Jan 16 1970 17:45:07 GMT-0500
. I could just multiply the value returned by unix()
but that seems sloppy to me. I suspect that what I am doing by calling unix()
is not exactly what I think it is. Do I need to specify some sort of format when calling unix()
? What am I missing here?
所有这些都很好。但是当我调用unix()
对象时,我得到了 value 1377907200
。然而,这对应于Fri Jan 16 1970 17:45:07 GMT-0500
。我可以乘以返回的值,unix()
但这对我来说似乎很草率。我怀疑我通过打电话所做的事情unix()
并不完全是我认为的那样。调用时是否需要指定某种格式unix()
?我在这里错过了什么?
回答by Matt Johnson-Pint
The answer provided by meagar is correct, from strictly a JavaScript / Unix time perspective. However, if you just multiply by 1000, you will loose any sub-second precision that might have existed in your data.
从严格的 JavaScript / Unix 时间角度来看,meagar 提供的答案是正确的。但是,如果您只是乘以 1000,您将失去数据中可能存在的任何亚秒级精度。
Moment.js offers two different methods, as described in the docs. .unix()
returns the value in seconds. It is effectively dividing by 1000 and truncating any decimals. You want to use the .valueOf()
method, which just returns the milliseconds without modification.
Moment.js 提供了两种不同的方法,如文档中所述。 .unix()
以秒为单位返回值。它有效地除以 1000 并截断任何小数。您想使用该.valueOf()
方法,该方法只返回毫秒而不进行修改。
回答by meagar
In JavaScript land, when you convert a Date
to an integer, you get a number of milliseconds since the unix epoch. Traditional Unix time is the number of secondssince epoch. Multiplying by 1000 is the correct option.
在 JavaScript 领域,当您将 a 转换Date
为整数时,您将获得自 unix 纪元以来的毫秒数。传统的 Unix 时间是自纪元以来的秒数。乘以 1000 是正确的选择。