Is the current time between 18:00 and 2:00

I have a schedule in the bar with dynamic opening and closing times, and I need to calculate whether the current time will be during today's opening hours.

The problem is that the opening and closing times are not on the same day. How to calculate if currentTime is within a certain time in a few days?

I am using jquery in this project.

+5
source share
5 answers

You can calculate this with javascripts Date Object like:

var start = new Date(2012,6,20,13).getTime();
var now = new Date().getTime();
var end = new Date(2012,6,21,2).getTime();

if( (start < now ) && (now < end )) {
  console.log("opened");
}
else {
 console.log("closed");
}

will be displayed open until tomorrow 2am, then it will be displayed closed.

you can look at this JSBin Example and change the start time to see how it changes

+3

Date(). getTime(); , ( 1 1970 ).

, , , , , , .

, Date().getTime(); +new Date;, . Google :). , + int.

+7

, jquery .

""? : , ?

, ..., 2 , " ". "timestamp" openTime && < closeTime ':

if(timestamp > openTime && timestamp <= Midnight || timestamp >= 0 && timestamp < closing time) {
     //Open/Close time
}

?

:

if((closeTime > openTime && timestamp > openTime && timestamp < closeTime) || //Normal time
(timestamp > openTime && timestamp < 86399) || //Before Midnight
(timestamp > 0 && timestamp < closeTime)) {    //After Midnight
    //Do Stuff
}

'closeTime' , , ... , , , , .

, ... , .

, :

if(timestamp < openTime && openTimePrevDay > closeTimePrevDay && timestamp > closeTimePrevDay) {
    //Bar is open
}

?

+1

If the closing time is before the opening time, it crosses the day, and you must define it differently:

if (closingTime >= openingTime) {
    // Open during the day
    return currentTime >= openingTime && currentTime < closingTime;
} else {
    // Open across midnight
    return currentTime >= openingTime || currentTime < closingTime;
}
0
source

You can take a look at the MomentJS library . It offers a good API for handling date and time.

0
source

All Articles