简体   繁体   中英

How to check the current time if it is between two times using momentjs?

This question was asked several times before but I'm stuck!

what I tried to do

    let now = moment().format('LT'); // 11:28 PM
    let close = moment('2019-04-26T22:00:18.000Z').format('LT'); // 1:00 AM
    let open = moment('2019-04-26T13:00:32.000Z').format('LT'); // 4:00 PM
    console.log(moment(now).isBetween(moment(open), moment(close))); // always return false
    console.log(moment(now).isBetween(moment(open), moment(close), "hour")); // always return false
    console.log(moment(now).isBetween(open, close, "hour")); // always return false
    console.log(moment(now).isBetween(open, close)); // always return false

Any idea why I'm getting always false?

If you just want to compare times, you can create a moment object at a certain hour and minute, and the other settings will default to today. Calling .format will return a string but doesn't modify the calling object. Your code is comparing today's date and time against times on a different day altogether, so it is always false. Also, there is no need to wrap a moment object in another call to Moment.

 // Opening and Closing Time data objects const openingTime = { hour: 8, minute: 00 }, closingTime = { hour: 20, minute: 00 }; // Create Moment objects const now = moment(), openToday = moment(openingTime), openYesterday = moment(openingTime).subtract(1, 'day'), closeToday = moment(closingTime), closeTomorrow = moment(closingTime).add(1, 'day'); let openForBusiness = false; if (openToday.isBefore(closeToday)) { openForBusiness = now.isBetween(openToday, closeToday); } else { openForBusiness = now.isBetween(openYesterday, closeToday) || now.isBetween(openToday, closeTomorrow); } console.log("openForBusiness:", openForBusiness); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM