Home > front end >  Run the code between specified hours in php
Run the code between specified hours in php

Time:01-17

I want to run my code from 21:00 to 08:00, for example. But my code does not work properly because when the clock reaches 24:00 (00:00), my code gets confused and cannot set 01:00. check 00:00 because it is a 24-hour clock.

I need this code for the dark mode of the site, so that my site will be in dark mode between a desired hour, for example, from 10 pm to 6 am.

Note: I may specify any hour for this task and I do not choose just one hour. For example, I may choose 21:00 to 3:00 am. It is random because the hours are chosen by my clients and I do not know what hours they choose. !!!

Can you guide me to make my code work correctly in 24 hours if I specify any hour?


    $hour = date('H');
    //$hour = 23;

    if( $hour > 22 && $hour < 8) {

      echo "Good night";

    }else{
      echo "Good Morning";
    }

CodePudding user response:

You can use the modulo operator to handle the 24-hour clock.

$start_hour = 21;
$end_hour = 8;
$current_hour = date('H');

// handle the 24-hour cycle
$current_hour = $current_hour % 24;

if($current_hour >= $start_hour || $current_hour < $end_hour) {
    echo "Good night";
} else {
    echo "Good morning";
}

This way it will work for any hours range you choose, as long as the start hour is greater than or equal to the end hour.

CodePudding user response:

You need opposite logic for 21:00 to 08:00 and 08:00 to 21:00. It's easier to see if you create a dedicated function:

function inRange(int $start, int $end, int $current = null): bool
{
    if ($current === null) {
        $current = date('H');
    }
    if ($start < $end) {
        return $current >= $start && $current <= $end;
    }
    return $current >= $start || $current <= $end;
}

Please note this is just an oversimplified example that's ignoring minutes and seconds. To make it more accurate, you can:

  • Pass full H:M:S / H:M strings
  • Convert everything to seconds (3600 * $h 60 * $m $s).

CodePudding user response:


    $wake_up = 8;
    $sleep = 23;
    if ($hour < $wake_up) {
        echo "Good night";
    } else if ($hour > $sleep) {
        echo "Good night";
    } else {
        echo "Good Morning";
    }

  • Related