Search code examples
javascriptdatemomentjs

Moment.js: Date between dates


I'm trying to detect with Moment.js if a given date is between two dates. Since version 2.0.0, Tim added isBefore() and isAfter() for date comparison.

Since there's no isBetween() method, I thought this would work:

var date = moment("15/02/2013", "DD/MM/YYYY");
var startDate = moment("12/01/2013", "DD/MM/YYYY");
var endDate = moment("15/01/2013", "DD/MM/YYYY");

if (date.isBefore(endDate) && date.isAfter(startDate) || (date.isSame(startDate) || date.isSame(endDate)) ) { alert("Yay!"); } else { alert("Nay! :("); }

I'm convinced there's got to be a better way to do this. Any ideas?


Solution

  • You can use one of the moment plugin -> moment-range to deal with date range:

    var startDate = new Date(2013, 1, 12)
      , endDate   = new Date(2013, 1, 15)
      , date  = new Date(2013, 2, 15)
      , range = moment().range(startDate, endDate);
    
    range.contains(date); // false