Javascript 在momentJS中new Date(..).getTime()不等于moment(..).valueOf()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31401446/
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
new Date(..).getTime() is not equal to moment(..).valueOf() in momentJS?
提问by thadeuszlay
new Date(..).getTime()
should return a timestamp in milliseconds. According to the documentation of momentJSthe expression moment(..).valueOf()
should do the same (return timestamp in milliseconds for a given date).
new Date(..).getTime()
应该以毫秒为单位返回时间戳。根据momentJS的文档,表达式moment(..).valueOf()
应该执行相同的操作(以毫秒为单位返回给定日期的时间戳)。
I checked with the following example data:
我检查了以下示例数据:
var timeStampDate = new Date("2015-03-25").getTime(); //timestamp in milliseconds?
> 1427241600000
var timeStampMoment = moment("03-25-2015", "MMDDYYYY").valueOf(); //timestamp in milliseconds?
> 1427238000000
As you can see the results were not the same.
如您所见,结果并不相同。
Now I'm searching for a function in momentJSthat returns to me the exact same data that the expression new Date(..).getTime()
.
现在我在momentJS中搜索一个函数,该函数返回给我的数据与表达式new Date(..).getTime()
.
回答by R. Oosterholt
Date constructor doc:
日期构造函数文档:
The UTC time zone is used to interpret arguments in ISO 8601 format that do not contain time zone information
UTC 时区用于解释不包含时区信息的 ISO 8601 格式的参数
moment constructor doc:
时刻构造函数文档:
Unless you specify a timezone offset, parsing a string will create a date in the current timezone
除非您指定时区偏移量,否则解析字符串将在当前时区创建一个日期
so specifying the timezone in the moment constructor results in the same behavior as Date:
因此在构造函数中指定时区会导致与 Date 相同的行为:
var timeStampMoment = moment("03-25-2015 +0000", "MM-DD-YYYY Z").valueOf(); //> 1427241600000
回答by iabw
When you pass in the same value to Date and moment (at least in Chrome a few years on), you get the same value from both values.
当您将相同的值传递给 Date 和 moment 时(至少在几年后的 Chrome 中),您会从这两个值中获得相同的值。
new Date("2015-03-25").getTime()
1427241600000
moment("03-25-2015", "MMDDYYYY").valueOf()
1427259600000
new Date("03-25-2015").getTime()
1427259600000
What you actually hit was just a different guess of the Date format in Date.parse
您实际命中的只是对Date.parse中的日期格式的不同猜测