Moment.js startOf problem

I am trying to get the start and end of the day (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 date startand endthe same. The date is endas expected, but the function startOfdoes what the function does endOf.

Perhaps something is missing me?

+4
source share
1 answer

Dates change and change by method calls. Your two dates are actually the same date object. That is, it day.startOf("day")returns a value dayboth times when you call it. However, you can make copies:

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

This creates two new instances.

+7
source

Source: https://habr.com/ru/post/1615270/


All Articles