Moment.js: Date between dates

后端 未结 8 1460
庸人自扰
庸人自扰 2020-11-27 11:18

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 compari

相关标签:
8条回答
  • 2020-11-27 11:57

    As Per documentation of moment js,

    There is Precise Range plugin, written by Rob Dawson, can be used to display exact, human-readable representations of date/time ranges, url :http://codebox.org.uk/pages/moment-date-range-plugin

    moment("2014-01-01 12:00:00").preciseDiff("2015-03-04 16:05:06");
    // 1 year 2 months 3 days 4 hours 5 minutes 6 seconds
    
    moment.preciseDiff("2014-01-01 12:00:00", "2014-04-20 12:00:00");
    // 3 months 19 days
    
    0 讨论(0)
  • 2020-11-27 11:58

    I do believe that

    if (startDate <= date && date <= endDate) {
      alert("Yay");
    } else {
      alert("Nay! :("); 
    }
    

    works too...

    0 讨论(0)
  • 2020-11-27 11:58
    if (date.isBefore(endDate) 
     && date.isAfter(startDate) 
     || (date.isSame(startDate) || date.isSame(endDate))
    

    is logically the same as

    if (!(date.isBefore(startDate) || date.isAfter(endDate)))
    

    which saves you a couple of lines of code and (in some cases) method calls.

    Might be easier than pulling in a whole plugin if you only want to do this once or twice.

    0 讨论(0)
  • 2020-11-27 12:02

    You can use

    moment().isSameOrBefore(Moment|String|Number|Date|Array);
    moment().isSameOrAfter(Moment|String|Number|Date|Array);
    

    or

    moment().isBetween(moment-like, moment-like);
    

    See here : http://momentjs.com/docs/#/query/

    0 讨论(0)
  • 2020-11-27 12:10

    Please use the 4th parameter of moment.isBetween function (inclusivity). Example:

    var startDate = moment("15/02/2013", "DD/MM/YYYY");
    var endDate = moment("20/02/2013", "DD/MM/YYYY");
    
    var testDate = moment("15/02/2013", "DD/MM/YYYY");
    
    testDate.isBetween(startDate, endDate, 'days', true); // will return true
    testDate.isBetween(startDate, endDate, 'days', false); // will return false
    
    0 讨论(0)
  • 2020-11-27 12:12

    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
    
    0 讨论(0)
提交回复
热议问题