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 badges1 Answer
Reset to default 15Dates 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.