0

I'm struggling to compare two times.

I need to print Current class going based on the current time.

Example: current time based class going on the college/school

var now = new Date();
var TwentyFourHour = now.getHours();
var hour = now.getHours();
var min = now.getMinutes();
var mid = 'PM';

if (min < 10) {
    min = "0" + min;
}
if (hour > 12) {
    hour = hour - 12;
}
if (hour == 0) {
    hour = 12;
}
if (TwentyFourHour < 12) {
    mid = 'AM';
}
Current_time = hour + ':' + min + ':' + mid;

start_time = "09:00:PM";
end_time = "10:00:PM";



if (parseInt(start_time) <= parseInt(Current_time) || parseInt(end_time) >= parseInt(Current_time)) {

    console.log("C programming class is going");
} else {
    console.log("No class are avalible");
}

OUTPUT:
C programming class is going....
B001ᛦ
  • 2,036
  • 6
  • 23
  • 31
Maseeha Tasneem
  • 111
  • 1
  • 1
  • 7

2 Answers2

0

It seems you are looking for the shortest path to have your homework done. Please check the references for Date function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

Some tips:

  • Make sure you understand how the Date object is created. You can use strings!
  • If you want to define date manually using each day, month , value, you can!
  • Check your strings.. are you sure "09:00:PM" is a valid string for date?
  • Are you sure you can use parseInt for parsing dates?

Anyway, you need to do more research.

Dharman
  • 30,962
  • 25
  • 85
  • 135
PM_sudo
  • 21
  • 3
0

The easiest way to check if a time is between a start and an end time is to store the time using unix time(https://en.wikipedia.org/wiki/Unix_time). It represents the time in seconds after 00:00:00 UTC on 1 January 1970. so you can do the following:

const startTime = 1624802400 // 27.6.21 16:00
const endTime = 1624809600 //27.6.21 18:00
const currentTime = Date.now()/1000

if(currentTime < endTime && currentTime > startTime){
    console.log('Class is going')
}
if(currentTime > endTime){
    console.log('Class ended')
}
if(currentTime < startTime){
    console.log('Class has not started')
}

Date.now() returns the current time in milliseconds so you need to divide it by 1000

Timm Nicolaizik
  • 357
  • 1
  • 11