Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate days to go until a particular date with momentjs

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());
like image 719
Highly Irregular Avatar asked Apr 16 '15 22:04

Highly Irregular


People also ask

How do you calculate the number of days between two dates of a moment?

Also you can use this code: moment("yourDateHere", "YYYY-MM-DD"). fromNow(). This will calculate the difference between today and your provided date.

How do I get time from Momentjs?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. moment().

Should you still use Momentjs?

Moment. js is a fantastic time & date library with lots of great features and utilities. However, if you are working on a performance sensitive web application, it might cause a huge performance overhead because of its complex APIs and large bundle size.

How do I compare two dates in Momentjs?

The momentjs provide the isSame() method to check date is the same as another date or not, if it returns true means the date is the same as another date. You can specify what you are checking like year , month , week , isoWeek , day , hour , minute , and second using isSame() second parameter like below example.


Video Answer


3 Answers

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());
like image 83
Bart Jedrocha Avatar answered Oct 16 '22 20:10

Bart Jedrocha


Just to add for anyone else that comes across this - there's actually a helper that does the phrasing etc for you:

https://momentjs.com/docs/#/displaying/to/

/* Retrieve a string describing the time from now to the provided date */
daysUntil: function(dateToCheckAgainst){
    return new moment().to(moment(dateToCheckAgainst));
}

// Sample outputs
"in three months"
"in two months"
"in 25 days"
like image 32
Chris Owens Avatar answered Oct 16 '22 19:10

Chris Owens


That's because months are zero indexed. So 5 is actually June ;)

like image 3
Tiago Fael Matos Avatar answered Oct 16 '22 18:10

Tiago Fael Matos