user3484136
user3484136

Reputation: 29

Check if the current time between specific time

In my database have start time and end time 24h format.I write a function to show result depend on time.

$day_start=06:00;
$day_end=22:59;

$night_start=23:00;
$night_end=05:59;

$dtarif=30USD;
$ntarif=80USD;

function showtarif($day_start,$day_end,$night_start,$night_end,$dtarif,$ntarif)
{


$current=date("H:i");

    if ($current =>$day_start && $current <=$day_end) {

    $absulate_tarif=$dtarif;

    }
    else if ($current >=$night_start && $current <=$night_end) {
       $absulate_tarif=$ntarif;
    }

 return $absulate_tarif;
}

when i call my function the it always show null.

Upvotes: 0

Views: 60

Answers (2)

Sharanya Dutta
Sharanya Dutta

Reputation: 4021

You have to remember two things:

  1. The comparison operators >= and <= are unable to compare strings. For that the built-in function strcmp is needed.

  2. A function can access only those variables which have been created inside the function (unless used with the global keyword).

In my opinion, you shouldn’t create variables like $day_start, $day_end, $night_start, $night_end, $dtarif and $ntarif. Just put their values at the right places and make your code more concise:

function showtarif(){
$current = date("H:i");
    if(strcmp($current, "06:00") >= 0 && strcmp($current, "22:59") <= 0){
    return "30USD";
    }
return "80USD";
}

DEMO

Upvotes: 1

Parag Tyagi
Parag Tyagi

Reputation: 8960

Enclose your time and amount in quotes

$day_start="06:00";
$day_end="22:59";

$night_start="23:00";
$night_end="05:59";

$dtarif="30USD";
$ntarif="80USD";

Upvotes: 0

Related Questions