Moody
Moody

Reputation: 164

Check if current time is between start time & end time in JavaScript

I'd like to find out how I can check if the current time is between 11am and 8pm in JavaScript.

Also, is there a way I can check how many minutes until 8pm from the current time?

Thanks!

Upvotes: 1

Views: 4040

Answers (7)

Dan P
Dan P

Reputation: 63

This function allows for ranges such as 10pm-4am as well

function isCurrentHourBetween(minHour, maxHour){
  if (maxHour > 23 || maxHour < 0) {
    console.error(maxHour, ' ~ Invalid Max Hour')
    return false
  }
  if (minHour > 23 || minHour < 0) {
    console.error(minHour, ' ~ Invalid Min Hour')
    return false
  }

  const currentHour = getCurrentHour() 
  // get the current hour with any of the ways listed in the other answers 
  // should be a number 0-23

  if (currentHour < 0 || currentHour > 23) {
    console.error(currentHour, ' ~ Invalid Current Hour')
    return false
  }

  if (minHour < maxHour) {
    if (currentHour >= minHour && currentHour <= maxHour) return true
    else return false
  } else if (minHour > maxHour) {
    if (currentHour >= minHour || currentHour <= maxHour) {
      return true
    } else return false
  } else {
    if (currentHour === minHour && currentHour === maxHour) return true
    else return false
  }
}

Upvotes: 0

topsoftwarepro
topsoftwarepro

Reputation: 822

I got the time using new Date(). and then used .getHours(), .getMinutes() and .getSeconds() to get the exact time.

I then used if (hours > 11 && hours < 20) to check if it was between 11am and 8pm.

I reduced the date from endTime (endTime was 8pm) which returned the difference in milliseconds so I converted it to minutes by dividing it by (1000 * 60).

Then I just put in the result inside divs.

The divs are updating every second.

Try out my code below!

function newTime() {
  var date = new Date();

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  if (hours > 12) {
    var hours = hours - 12;
  }
  if (hours < 10) {
    hours = "0" + hours;
  }
  if (minutes < 10) {
    minutes = "0" + minutes;
  }
  if (seconds < 10) {
    seconds = "0" + seconds;
  }

  var time = hours + ":" + minutes + ":" + seconds;
  $("#answer1").html("The time now is: " + time);
  
  hours = date.getHours();
  
  if (hours >= 11 && hours < 20) {
    $("#answer2").html("The current time is between 11am and 8pm!");
    let endTime = (new Date(date)).setHours(20, 0, 0, 0);
    let minsLeft = Math.ceil((endTime - date) / (1000 * 60));
    $("#answer3").html("Minutes left till 8pm: " + minsLeft);
  } else {
    $("#answer2").html("The current time is not between 11am and 8pm!");
  }

}

setInterval(newTime, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="answer1"></div>
<div id="answer2"></div>
<div id="answer3"></div>

Upvotes: 0

Rohit Tagadiya
Rohit Tagadiya

Reputation: 3730

I think you want something like this..

checkTime();

function checkTime() {
    var date = new Date(); // current time
    var hours = date.getHours();
    var mins = date.getMinutes();
    var day = date.getDay();
    var totalMins = (hours * 60) + mins;
    var targetMins = 20 * 60
    var remainMins = targetMins - totalMins
    
    if(hours >= 11 && hours < 20) {
      document.getElementById("text").innerHTML = "Yes Current time is between 11am to 8pm And " + remainMins + " mins left to be time 8pm";
      console.log("Yes Current time is between 11am to 8pm And " + remainMins + " mins left to be time 8pm");
    }
    else {
      document.getElementById("text").innerHTML = "There is " + remainMins + " mins left to be time 8pm";
      console.log("There is " + remainMins + " mins left to be time 8pm");
    }
}
<p id="text"></p>

Upvotes: 4

Cat
Cat

Reputation: 4226

Once you have a JavaScript date object, you can use the getHours method to get the hour of the day (in 24-hr time), then just compare the numbers.

To get elapsed minutes, you can subtract one date object from another, then divide by 60,000 (the number of milliseconds in a minute):

// Checks if current time is between 11am and 8pm
const
  date = new Date();
  hours = date.getHours(),
  isBetween = (hours >= 11) && (hours < 20),
  readableDate = date.toLocaleString();
console.log(`"${readableDate}" is between 11am and 8pm?: ${isBetween}`);

// Calculates minutes until 8pm
  const
    oneMinute = 60 * 1000, // JS times are measured in milliseconds
    eightPM = new Date();
  eightPM.setHours(20, 0, 0, 0); // Sets the new date object's time to 8pm
  const
    millisecsDuration = eightPM - date, // **Assumes it's before 8pm!
    minsDuration = parseInt(millisecsDuration / oneMinute);
  console.log(`Minutes until 8pm: ${minsDuration}`);

Upvotes: 1

Karan
Karan

Reputation: 12619

You can get current time with new Date().

Set hour, minute, second, milliseconds values with .setHours(11, 0, 0, 0).

You can compare it with if (fromTime <= currentTime && currentTime <= toTime) {.

toTime - currentTime will return difference in milliseconds so convert it ti minutes by dividing it with (1000*60).

Try complete code below.

function checkTime(currentTime) {
  let fromTime = new Date(currentTime).setHours(11, 0, 0, 0);
  let toTime = (new Date(currentTime)).setHours(20, 0, 0, 0);

  console.log(currentTime.toString());
  
  if (fromTime <= currentTime && currentTime <= toTime) {
    console.log('Time is between 11AM and 8PM');

    let mins = Math.ceil((toTime - currentTime) / (1000 * 60));
    console.log('Minutes left to 8PM = ' + mins);
  } else {
    console.log('Time is not between 11AM and 8PM');
  }
}

let currentTime = new Date();
checkTime(currentTime);
let customTime = new Date(2020, 10, 10, 15, 0, 0, 0);
checkTime(customTime);

Upvotes: 3

This is my approach:

function dateCompareToday() {
    const today = new Date();
    return new Date(today.setHours(11,0,0)) > today &&  today > new Date(today.setHours(20,0,0))

}

console.log(dateCompareToday())

And with parameters:

function dateCompareToday(a, b) {
    const today = new Date();
    return new Date(today.setHours(a,0,0)) > today &&  today > new Date(today.setHours(b,0,0))

}

console.log(dateCompareToday(11,20))

Upvotes: 1

Rohan Shenoy
Rohan Shenoy

Reputation: 895

Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); 
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);

console.log(check > from && check < to)

Upvotes: -1

Related Questions