Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js startOf issue

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?

like image 600
artooras Avatar asked Nov 10 '15 15:11

artooras


People also ask

Is moment JS still used?

Moment.js has been successfully used in millions of projects, and we are happy to have contributed to making date and time better on the web. As of September 2020, Moment gets over 12 million downloads per week! However, Moment was built for the previous era of the JavaScript ecosystem. The modern web looks much different these days.

How to load moment in a RequireJS environment?

Note: To allow moment.js plugins to be loaded in requirejs environments, moment is created as a named module. Because of this, moment must be loaded exactly as as "moment", using paths to determine the directory. Requiring moment with a path like "vendormoment" will return undefined.

How to get the moment object from the date in JavaScript?

Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object. To get this wrapper object, simply call moment () with one of the supported input types.

How to check if a moment is the same in JavaScript?

moment ().isSame (Moment|String|Number|Date|Array); moment ().isSame (Moment|String|Number|Date|Array, String); Check if a moment is the same as another moment. The first argument will be parsed as a moment, if not already so.


1 Answers

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.

like image 178
Pointy Avatar answered Sep 24 '22 16:09

Pointy