Moment()vs预定义的Moment()日期

时间:2016-09-21 15:23:48

标签: javascript date datetime momentjs

我对Moment函数的工作方式有点困惑(例如startOf()weekday()等)。

我的问题是:如何从预定义的日期获得一周的开始?

考虑9/21/16上的这两个电话:

moment().startOf('week') // Returns a moment object with date set to Sun Sep 18 2016 ...

VS

moment(new Date("9/21/16")).startOf('week') // Returns a moment object with date set to Wed Sep 21 2016 ...

为什么这些行为不一样?使用weekday(0)代替startOf('week')

时也是如此

2 个答案:

答案 0 :(得分:6)

您不能简单地将Date构造函数用于您喜欢的任何日期格式。例如,在我使用Firefox的系统上,new Date("9/21/16")将Date对象设置为1916-09-20T22:00:00.000Z

使用ISO 8601格式,甚至更好,parse your string with Moment itself

moment("9/21/16", "MM/DD/YY")

答案 1 :(得分:0)

您如何知道moment(new Date("9/21/16")).startOf('week')正在返回Wed Sep 21 2016?你在寻找返回的物体吗?如果是这样,我认为你只是看到输入日期。您应该使用moment.format()函数来获取实际日期:

// "September 18, 2016"
moment().startOf("week").format("LL");

// "September 18, 2016"
moment("9/21/16", "MM/DD/YY").startOf("week").format("LL");

// "September 18, 2016" on my system (not recommended)
moment(new Date("9/21/16")).startOf("week").format("LL");
相关问题