为什么在分配给变量时,moment.js会给出不同的结果?
问题描述:
我一直在调试这个一会儿现在仍然没有能够弄明白。 在_d
时如何从在_i
的时间不同具体请看。为什么?为什么在分配给变量时,moment.js会给出不同的结果?
var date = new Date('Fri, 06 Jan 2017 21:30:00 -0000')
const momentDate = moment(date)
console.log(`momentDate: `, momentDate);
console.log(`moment(date): `, moment(date));
答
那么是什么原因导致的问题是我有被改写值startOf('day')
一个反应成分。如果您使用的时刻流入您的应用程序到时刻对象所有字符串日期转换,如果遇到错误,一定要看看你的组件,而不是仅仅在为API调用convertToMoment
按摩功能。
更重要的是,直到那一刻3.0,所有时刻的对象是可变的,所以,如果你这样做:
var a = moment()
var b = a.startOf('day')
console.log(a.format('LLL')) // January 22, 2017 12:00 AM
console.log(b.format('LLL')) // January 22, 2017 12:00 AM
解决这个问题的唯一方法可以是:
// use the cool `frozen-moment` package (which is basically a polyfill)
var a = moment().freeze()
var b = a.startOf('day')
console.log(a.format('LLL')) // January 22, 2017 2:17 AM
console.log(b.format('LLL')) // January 22, 2017 12:00 AM
// or type `.clone()` everytime you want to use a cool function
var a = moment()
var b = a.clone().startOf('day')
console.log(a.format('LLL')) // January 22, 2017 2:17 AM
console.log(b.format('LLL')) // January 22, 2017 12:00 AM
一个创建瞬间的点.js是使用'Date'构造函数解析字符串是一个糟糕的想法(tm)。相反,使用'moment(string,format)','format'提供库如何解析'string'。 –
的可能的复制[momentjs内部对象是什么 “\ _d” 与 “\ _i”](http://stackoverflow.com/questions/28126529/momentjs-internal-object-what-is-d-vs-i) –
@MikeMcCaughan我真的开始了,但我得到了同样的结果。 [CODE /输出(http://imgur.com/a/BHxFk) –