最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - moment.js startOf issue - Stack Overflow

programmeradmin3浏览0评论

I am trying to get the start and end of a day (which is a few days from today) using moment.js. This is the code I have:

var today = moment();
var day = today.add(-5, "days");
var startOfDay = day.startOf("day");
var endOfDay = day.endOf("day");

console.log("today " + today.format());
console.log("day " + day.format());
console.log("start " + startOfDay.format());
console.log("end " + endOfDay.format());

And these are the logs:

I2015-11-10T15:19:02.930Z]today 2015-11-10T15:19:02+00:00
I2015-11-10T15:19:02.931Z]day 2015-11-05T15:19:02+00:00
I2015-11-10T15:19:02.932Z]start 2015-11-05T23:59:59+00:00
I2015-11-10T15:19:02.933Z]end 2015-11-05T23:59:59+00:00

As you can see, the start and end dates are exactly the same. The end date is as expected, however, the startOf function appears to be doing exactly what the endOf function does.

Is there perhaps something I am missing?

I am trying to get the start and end of a day (which is a few days from today) using moment.js. This is the code I have:

var today = moment();
var day = today.add(-5, "days");
var startOfDay = day.startOf("day");
var endOfDay = day.endOf("day");

console.log("today " + today.format());
console.log("day " + day.format());
console.log("start " + startOfDay.format());
console.log("end " + endOfDay.format());

And these are the logs:

I2015-11-10T15:19:02.930Z]today 2015-11-10T15:19:02+00:00
I2015-11-10T15:19:02.931Z]day 2015-11-05T15:19:02+00:00
I2015-11-10T15:19:02.932Z]start 2015-11-05T23:59:59+00:00
I2015-11-10T15:19:02.933Z]end 2015-11-05T23:59:59+00:00

As you can see, the start and end dates are exactly the same. The end date is as expected, however, the startOf function appears to be doing exactly what the endOf function does.

Is there perhaps something I am missing?

Share Improve this question edited Nov 10, 2015 at 15:31 artooras asked Nov 10, 2015 at 15:26 artoorasartooras 6,80511 gold badges55 silver badges88 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 15

Dates are mutable, and are altered by the method calls. Your two dates are both actually the same date object. That is, day.startOf("day") returns the value of day both times you call it. You can make copies however:

var startOfDay = moment(day).startOf("day");
var endOfDay = moment(day).endOf("day");

That constructs two new instances.

发布评论

评论列表(0)

  1. 暂无评论