Sunil
Sunil

Reputation: 21396

Check if current time is between two given times in JavaScript

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)

Upvotes: 18

Views: 45070

Answers (7)

Daniel Tovesson
Daniel Tovesson

Reputation: 2590

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())
  );
};

Upvotes: 0

Deepak A S
Deepak A S

Reputation: 64

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');
}

Upvotes: -1

Abdeali Chandanwala
Abdeali Chandanwala

Reputation: 8828

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.

Upvotes: 3

James Hay
James Hay

Reputation: 7315

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());

Upvotes: 9

Mcm
Mcm

Reputation: 119

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);

Upvotes: 1

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

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

Upvotes: 22

Mahmal Sami
Mahmal Sami

Reputation: 709

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)

Upvotes: 1

Related Questions