Moment.js: Date between dates

后端 未结 8 1495
庸人自扰
庸人自扰 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 12:12

    Good news everyone, there's an isBetween function! Update your library ;)

    http://momentjs.com/docs/#/query/is-between/

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

    In versions 2.9+ there is an isBetween function, but it's exclusive:

    var compareDate = 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");
    
    // omitting the optional third parameter, 'units'
    compareDate.isBetween(startDate, endDate); //false in this case
    

    There is an inclusive workaround ...
    x.isBetween(a, b) || x.isSame(a) || x.isSame(b)

    ... which is logically equivalent to
    !(x.isBefore(a) || x.isAfter(b))


    In version 2.13 the isBetween function has a fourth optional parameter, inclusivity.

    Use it like this:

    target.isBetween(start, finish, 'days', '()') // default exclusive
    target.isBetween(start, finish, 'days', '(]') // right inclusive
    target.isBetween(start, finish, 'days', '[)') // left inclusive
    target.isBetween(start, finish, 'days', '[]') // all inclusive
    

    More units to consider: years, months, days, hours, minutes, seconds, milliseconds

    Note: units are still optional. Use null as the third argument to disregard units in which case milliseconds is the default granularity.

    Visit the Official Docs

    0 讨论(0)
提交回复
热议问题