Check if current time is between two given times in JavaScript
Asked Answered
K

7

18

I have two variables called 'startTime' and 'endTime'. I need to know whether current time falls between startTime and EndTime. How would I do this using JavaScript only?

var startTime = '15:10:10';
var endTime = '22:30:00';
var currentDateTime = new Date(); 
//is current Time between startTime and endTime ???

UPDATE 1:

I was able to get this using following code. You can check out the code at: https://jsfiddle.net/sun21170/d3sdxwpb/1/

var dt = new Date();//current Date that gives us current Time also

var startTime = '03:30:20';
var endTime = '23:50:10';

var s =  startTime.split(':');
var dt1 = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(),
                   parseInt(s[0]), parseInt(s[1]), parseInt(s[2]));

var e =  endTime.split(':');
var dt2 = new Date(dt.getFullYear(), dt.getMonth(),
                   dt.getDate(),parseInt(e[0]), parseInt(e[1]), parseInt(e[2]));

alert( (dt >= dt1 && dt <= dt2) ? 'Current time is between startTime and endTime' : 
                                  'Current time is NOT between startTime and endTime');
alert ('dt = ' + dt  + ',  dt1 = ' + dt1 + ', dt2 =' + dt2)
Knoxville answered 21/4, 2015 at 23:59 Comment(3)
So format the time fraction from the currentDateTime as HH:mi:ss and compare strings as-is.Shockley
@zerkms, Can you provide it as an answer?Knoxville
can you provide it as an answer? :-)Shockley
F
21
var startTime = '15:10:10';
var endTime = '22:30:00';

currentDate = new Date()   

startDate = new Date(currentDate.getTime());
startDate.setHours(startTime.split(":")[0]);
startDate.setMinutes(startTime.split(":")[1]);
startDate.setSeconds(startTime.split(":")[2]);

endDate = new Date(currentDate.getTime());
endDate.setHours(endTime.split(":")[0]);
endDate.setMinutes(endTime.split(":")[1]);
endDate.setSeconds(endTime.split(":")[2]);


valid = startDate < currentDate && endDate > currentDate
Fimbria answered 22/4, 2015 at 0:27 Comment(4)
You mutate the same reference. So startDate === endDateShockley
@Shockley i edited it so startDate and endDate is copied from currentDateFimbria
what if you had somehing like startTime = "23:00:00" and endTime = "3:00:00"? That is, if the time period spans midnight?Modillion
@Modillion the question is related to the same day, as it compares times, in the case you mentioned dates should be included for that to workFimbria
M
9

You can possibly do something like this if you can rely on your strings being in the correct format:

var setDateTime = function(date, str){
    var sp = str.split(':');
    date.setHours(parseInt(sp[0],10));
    date.setMinutes(parseInt(sp[1],10));
    date.setSeconds(parseInt(sp[2],10));
    return date;
}

var current = new Date();

var c = current.getTime()
  , start = setDateTime(new Date(current), '15:10:10')
  , end = setDateTime(new Date(current), '22:30:00');

return (
    c > start.getTime() && 
    c < end.getTime());
Machinate answered 22/4, 2015 at 0:19 Comment(2)
This code is subject to race condition: if the start = line runs 1ms before midnight and end = runs exactly in the midnight - you'll get false positive result.Shockley
4 and a half years late, but updated for the race conditionMachinate
S
3

I wanted to compare a time range in the day ... so I wrote this simple logic where the time is converted into minutes and then compared.

const marketOpen = 9 * 60 + 15 // minutes
const marketClosed = 15 * 60 + 30 // minutes
var now = new Date();
var currentTime = now.getHours() * 60 + now.getMinutes(); // Minutes since Midnight

if(currentTime > marketOpen && currentTime < marketClosed){ }

Note that I have not taken UTC minutes and hours since I want to use the local time, In my case it was IST time.

Segregation answered 8/10, 2020 at 14:36 Comment(0)
R
1

A different approach: First, convert your currentDate

var totalSec = new Date().getTime() / 1000;
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;

var numberToCompare = hours*10000+minutes*100+seconds;

cf Convert seconds to HH-MM-SS with JavaScript?

Then compare:

(numberToCompare < (endTime.split(':')[0]*10000+endTime.split(':')[1]*100+endTime.split(':')[2]*1)

or

(numberToCompare > (endTime.split(':')[0]*10000+endTime.split(':')[1]*100+endTime.split(':')[2]*1)
Racemose answered 22/4, 2015 at 0:22 Comment(0)
P
1

Just another way I have for matching periods in a day, precision is in minutes, but adding seconds is trivial.

function isValid(date, h1, m1, h2, m2) {
  var h = date.getHours();
  var m = date.getMinutes();
  return (h1 < h || h1 == h && m1 <= m) && (h < h2 || h == h2 && m <= m2);
}

isValid(new Date(), 15, 10, 22, 30);
Preciosa answered 12/6, 2018 at 17:54 Comment(1)
function isValid(date, h1, m1, h2, m2) { var h = date.getHours(); var m = date.getMinutes(); return (h1 < h || (h1 == h && m1 <= m)) && (h < h2 || (h == h2 && m <= m2)); } isValid(new Date(), 15, 10, 22, 30); Added the brackets, not to mistify the developers.Edibles
U
0

If the time spans over midnight you need to do this:

const timeStringToDate = (timeString: string, now: Date) => {
  const [hours, minutes] = timeString.split(':');
  const date = new Date(now);
  date.setHours(parseInt(hours, 10), parseInt(minutes, 10), 0, 0);
  return date;
};

export const isDateBetweenTimes = (
  date: Date,
  startTime: string,
  endTime: string,
) => {
  const startDate = timeStringToDate(startTime, date);
  const endDate = timeStringToDate(endTime, date);

  // If interval is e.g. 23:00 - 01:00, then we need to add a day to the end date
  if (startDate.getTime() >= endDate.getTime()) {
    endDate.setDate(endDate.getDate() + 1);
  }

  // Need to compare with tomorrows date if interval is e.g. 23:00 - 01:00 and date is 00:30
  // Otherwise the comparison would only be; is today 00:30 between today 23:00 and tomorrow 01:00
  const dateTomorrow = new Date(date);
  dateTomorrow.setDate(date.getDate() + 1);

  return (
    (date.getTime() >= startDate.getTime() &&
      date.getTime() <= endDate.getTime()) ||
    (dateTomorrow.getTime() >= startDate.getTime() &&
      dateTomorrow.getTime() <= endDate.getTime())
  );
};
Unquestionable answered 22/2 at 15:19 Comment(0)
R
-1

I use this...

// Get the current time
const currentTime = new Date();

// Set the start and end times
const startTime = new Date();
startTime.setHours(9, 0, 0); // Replace with your start time

const endTime = new Date();
endTime.setHours(18, 0, 0); // Replace with your end time

// Check if the current time is between the start and end times
if (currentTime >= startTime && currentTime <= endTime) {
  console.log('Current time is between the specified times');
} else {
  console.log('Current time is not between the specified times');
}
Ridinger answered 15/11, 2023 at 21:7 Comment(1)
This the same solution as the currently accepted one.Tinworks

© 2022 - 2024 — McMap. All rights reserved.