Reputation: 63587
I want to have code in a loop that only runs if it is before 5pm on any day.
What code would do this?
IF (current_time < 5:00pm) {
// Do stuff
}
Upvotes: 0
Views: 2229
Reputation: 3009
Simple one that gets the job done:
if (date('H') < 17)
{
// DO SOMETHING
}
Just remember that this date comes from the server. So, if the client is in another timezone, that may not work as required. The good thing about this, is that the user can't change his computer date in order to trick the site into something.
And if you want to do that with javascript (where the value will come from the user's computer), just do the following:
var today = new Date();
if (today.getHours() < 17)
{
// DO SOMETHING
}
Upvotes: 4
Reputation: 8509
In short...
$t = time(); # or any other timestamp
if (date('H', $t) < 17) {
// Do stuff
}
Works for any day
Note: Make sure your timezone is correct (check php config or just use date_default_timezone_set function before calling date function)
Upvotes: 0
Reputation: 168685
This solution uses the nice PHP5 DateTime
class, and avoids the clunky old strtotime()
function:
$hoursNow = new DateTime()->format('H');
if($hoursNow < 17) {
....
}
Upvotes: 6