Max Baldwin
Max Baldwin

Reputation: 3472

Moment JS Returning Incorrect Value

I am having some issues with the Moment JS NPM. I have a date in the past set to Jan 31st for testing. It is returning as 1 from today's date. Take a look at my code and screenshots below:

var tz = -5,
   thisYear = moment().utc(tz).year(),
// plus one because Moment starts month at 0
   thisMonth = moment().utc(tz).month() + 1,
   today = moment().utc(tz).date(),
   thisHour = moment().utc(tz).hour(),
   start = moment([2015, 1, 31, 15]),
   now = moment([thisYear, thisMonth, today, thisHour]),
   daysPast = now.diff(start, 'days');

console.log(thisYear, thisMonth, today, thisHour);
console.log(2015, 1, 31, 15);
console.log(daysPast);

This is what is getting returned in the console:

enter image description here

When I change the date to the first of February, it returns correctly:

enter image description here

Anyone have any ideas why Moment is returning incorrectly with the past month?

Upvotes: 0

Views: 885

Answers (2)

RobG
RobG

Reputation: 147343

Just to clarify zerkms answer, where you have:

thisMonth = moment().utc(tz).month() + 1,

you are setting thisMonth to 2 (if run in Feburary), then when you do:

start = moment([2015, 1, 31, 15]),

you are creating a date for 31 February, which doesn't exist so a date for 3 March is created.

Then when you do:

now = moment([thisYear, thisMonth, today, thisHour]),

remember that you incremented thisMonth by one, so it creates a date for 4 March, not 4 February (i.e. a month number of 2 creates a date for March).

The difference between 3 March and 4 March is one day.

Upvotes: 1

zerkms
zerkms

Reputation: 254886

In js months start with 0. So 2015, 1, 31 == 31st of February

Which is interpreted as March, 3rd which is exactly one day behind March, 4th

If you want to manipulate with dates - use the corresponding momentjs methods instead: http://momentjs.com/docs/#/manipulating/

Upvotes: 4

Related Questions