[英]How to handle two different times if they are not in the same day?
我正在處理餐廳的開放時間和關閉時間,我在用時間來解析時間,它可以正常工作,但是在某些情況下,它無法正常工作。如果餐廳在9:00 AM開放,在1:00 AM關閉(下一個)一天),無論何時,餐廳都會關閉。
if (current_time.isBetween(opening_hour, close_hour)) {
console.log('its open');
} else {
console.log('its closed');
}
我對這些問題做實際上是說,餐廳的開放兩次。 一旦從00:00至01:00,一次從09:00至00:00。 這樣,如果時間驗證了這些間隔中的任何一個,則餐廳必須營業。
這種方法是非常相似,你會如何處理,例如,午休時間,其中一家商店或餐廳12:00至14:00,下午關閉。
對於不提及日期的通用解決方案,您還可以先測試close_hour是否在open_hour之前,如果是,請使用isAfter(opening_hour) || isBefore(opening_hour)
isAfter(opening_hour) || isBefore(opening_hour)
:
注意:如果close_hour
不是momentJs中,第一行是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');
}
}
您可以將日期和時間一起使用。 或者您也可以將日期和時間轉換為紀元,然后嘗試比較
對於例如
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
現在,您可以編寫一個函數來檢查CURRENT_TIME是D1和D2之間。
另一種方法是節省開放時間和工作時間:
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');
}
您還應該將打開/關閉字符串更改為矩對象。
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")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.