Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  172] [ 7]  / answers: 1 / hits: 20104  / 9 Years ago, thu, april 16, 2015, 12:00:00

I want to count down the days until a particular event using momentjs but I'm getting an unexpected result.



With today's date being 17th April, and the event date being 14th May, I want the resulting number of days to be 27, however my code gives me a result of 57. What's wrong?



function daysRemaining() {
var eventdate = moment([2015, 5, 14]);
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());

More From » momentjs

 Answers
6

When creating a moment object using an array, you have to take note that months, hours, minutes, seconds, and milliseconds are all zero indexed. Years and days of the month are 1 indexed. This is to mirror the native Date parameters.



Reference



So either change the month to 4 to reflect May or parse the date as an ISO 8601 string



function daysRemaining() {
var eventdate = moment(2015-05-14);
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());

[#67038] Wednesday, April 15, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ignacio

Total Points: 467
Total Questions: 128
Total Answers: 79

Location: Luxembourg
Member since Tue, Mar 14, 2023
1 Year ago
ignacio questions
;