简体   繁体   中英

How to handle two different times if they are not in the same day?

I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working, If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .

   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

What I do for such problems is actually say that the restaurant is open twice. Once from 00:00 to 01:00 and once from 09:00 to 00:00. This way, if the time validates either of those intervals, the restaurant must be open.

This approach is very similar to how you would handle, for example, lunch breaks where a store or restaurant is closed between 12:00 and 14:00 in the afternoon.

For a generic solution without mention of date, you can also test first if close_hour is before opening_hour, and if the case, use isAfter(opening_hour) || isBefore(opening_hour) isAfter(opening_hour) || isBefore(opening_hour) :

NOTE: if close_hour is not a momentJs, the first line would be if (moment(close_hour, 'hh:mm').isAfter(opening_hour)) {

if (close_hour.isAfter(opening_hour)) {
    if (current_time.isBetween(opening_hour, close_hour)) {
        console.log('its open');
    } else {
        console.log('its closed');
    }
} else {
    if (current_time.isAfter(opening_hour) || current_time.isBefore(close_hour)) {
        console.log('its open');
    } else {
        console.log('its closed');
    }
}

You can use date along with the time. Or you can also convert the date and time to epoch and then try comparing

For Eg-

let d1= new Date('1-1-2019').getTime(); //1546281000000
let d2= new Date('1-2-2019').getTime(); //1546367400000

let current_time= new Date().getTime(); // gives current epoch

Now you can write a function to check if the current_time is between d1 and d2.

Another approach is to save opening hour and duration of work:


const opening_hour = moment('9:00am', 'hh:mm');
const current_time = moment();

const duration = 16 * 60; //duration in minutes, 16 hours

if (current_time.isBetween(opening_hour, opening_hour.clone().add(duration, 'minutes'))) {
     console.log('its open');
} else {
     console.log('its closed');
}

You should change the open/close strings to moment object as well.

var opening_time = moment("10:40", 'hh:mm')
var closing_time = moment("23:00", 'hh:mm:ss')

if (moment().isBetween(opening_time, closing_time)) {
  console.log("Open");
} else {
  console.log("Close")
}

https://jsfiddle.net/w7e028fg/

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