Developer
Developer

Reputation: 2706

How to validated time in PHP?

Hi i want to validated time between 11PM to 7AM. But not working.

Please check my code:

<?php
$curTime=date('G:i');
if(($curTime >= '23:00') && ($curTime <= '7:00')){
   echo "Working...";
   //some code here...
}else{
   echo "Sorry! this app not working at this time. Please use this app between 11pm to 7am <br><br>Thanks";
}
?>

I have checked this code after 11:00PM but it is not working.

Please help me.

Upvotes: 0

Views: 125

Answers (3)

user3232725
user3232725

Reputation: 218

<?php
$curTime=date('H');
if(($curTime >= 23) || ($curTime < 7)){
   echo "Working...";
   //some code here...
}else{
   echo "Sorry! this app not working at this time. Please use this app between 11pm to 7am <br><br>Thanks";
}
?>

You cannot compare strings like that. It is not logical. Use either just the hour or: HourMin without the ':' sign. Those you can use math one ;)

Upvotes: 2

Legionar
Legionar

Reputation: 7597

This will work from 23:00:00 - 06:59:59

<?php
$curTime=date('H');
if(($curTime >= 23) || ($curTime <= 6)){
   echo "Working...";
   //some code here...
}else{
   echo "Sorry! this app not working at this time. Please use this app between 11pm to 7am <br><br>Thanks";
}
?>

Hope, you dont need, it to work exactly at 07:00:00 ;-)

Upvotes: 0

John Conde
John Conde

Reputation: 219814

  • 11PM is 23 hours, not 11.
  • Time can't be both greater than 11pm and less than 7am.
  • You're comparing strings and not actual time.

Here's an example using DateTime() which make the logic a little bit clearer.

<?php
$curTime = new DateTime();
$am = new DateTime('07:00');
$pm = new DateTime('23:00');
if(($curTime < $pm) && ($curTime > $am)){
   echo "Working...";
   //some code here...
}else{
   echo "Sorry! this app not working at this time. Please use this app between 11pm to 7am <br><br>Thanks";
}
?>

Upvotes: 0

Related Questions