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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With