How to use Moment.JS to check whether the current time is between 2 times

前端 未结 3 1990
情深已故
情深已故 2020-12-15 15:00

Say the current time is 09:34:00 (hh:mm:ss), and I have two other times in two variables:

var beforeTime = \'08:34:00\',
    afterT         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 15:27

    I had to use isBetween and isSame in my case to cover the before and after time I used in the isBetween condition.

    function getTimeCategory(time) {
      let timeCategory = '';
      const timeFormat = 'HH:mm:ss';
    
      if (
        time.isBetween(moment('00:00:00', timeFormat), moment('04:59:59', timeFormat)) ||
        time.isSame(moment('00:00:00', timeFormat)) ||
        time.isSame(moment('04:59:59', timeFormat))
      ) {
        timeCategory = 'DAWN';
      } else if (
        time.isBetween(moment('05:00:00', timeFormat), moment('11:59:59', timeFormat)) ||
        time.isSame(moment('05:00:00', timeFormat)) ||
        time.isSame(moment('11:59:59', timeFormat))
      ) {
        timeCategory = 'MORNING';
      } else if (
        time.isBetween(moment('12:00:00', timeFormat), moment('16:59:59', timeFormat)) ||
        time.isSame(moment('12:00:00', timeFormat)) ||
        time.isSame(moment('16:59:59', timeFormat))
      ) {
        timeCategory = 'NOON';
      } else if (
        time.isBetween(moment('17:00:00', timeFormat), moment('23:59:59', timeFormat)) ||
        time.isSame(moment('17:00:00', timeFormat)) ||
        time.isSame(moment('23:59:59', timeFormat))
      ) {
        timeCategory = 'NIGHT';
      }
    
      return timeCategory;
    }
    

提交回复
热议问题