Checking if current time is falling in a time interval (24 hours) using jQuery

This is not about dates, time.

I don't know how you could confuse the two

What i have done so far:

At the moment, I can decide whether the current time will fall in the time range until it is 00:00 (12AM) or later.

This is because my current if condition looks only:

current time > startTime and current time < endTime

if (currentTime > startTime && currentTime < endTime) {
    green
} else {
    red
}

Please see the snippet I included to better understand the problem.

var shiftStartWorking = '00:00',
  shiftEndWorking = '08:00',
  shiftStartNotWorking = '17:00',
  shiftEndNotWorking = '00:00';

$('#current').text(moment().format('HH:mm'));

if (moment().format("HH:mm") > shiftStartWorking && moment().format("HH:mm") < shiftEndWorking) {

  $('#working').attr('style', 'color: green');

} else {

  $('#working').attr('style', 'color: red');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

<div>Current Time: <span id="current"></span>
</div>

<br />

<div>
  <span>Working version</span> -
  <span id="working">00:00 - 08:00</span>
</div>
Run codeHide result
+4
source share
1 answer

Using moment, you can compare moment objects instead of strings. You can check if the current time is within your range using isBetween.

Edit:

Moment ( ), , ( ), . , ( ).

# 2: , , . .

# 3: .

:

function isNowBetweenTime(startTime, endTime){
  // Creating moment objects for the current day at the given time
  var startMom = moment(startTime, 'HH:mm');
  var endMom   = moment(endTime, 'HH:mm');
  
  if ( startMom.isAfter(endMom) ){
    endMom.add(1, 'd');
  }
  
  return moment().isBetween(startMom, endMom);
}

var shiftStartWorking = '16:00',
  shiftEndWorking = '23:00',
  shiftStartNotWorking = '17:00',
  shiftEndNotWorking ='00:00';

$('#current').text(moment().format('HH:mm'));

if( isNowBetweenTime(shiftStartWorking, shiftEndWorking) ) {
  $('#working').attr('style', 'color: green');
} else {
  $('#working').attr('style', 'color: red');
}

if( isNowBetweenTime(shiftStartNotWorking, shiftEndNotWorking) ){
  $('#notWorking').attr('style', 'color: green');
} else {
  $('#notWorking').attr('style', 'color: red');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

<div>Current Time: <span id="current"></span>
</div>

<br />

<div>
  <span>Working version</span> -
  <span id="working">16:00 - 23:00</span>
</div>

<br />

<div>
  <span>Non Working version</span> -
  <span id="notWorking">17:00 - 00:00</span>
</div>
Hide result
+3

Source: https://habr.com/ru/post/1650146/


All Articles