Running code between certain times - php

I have php code that is suppose to run between 04:00am and 05:00am but it does not run, i cant see the problem with this?
$begin = new DateTime('04:30');
$end = new DateTime('05:00');
while (!connection_aborted() || PHP_SAPI == "cli") {
$now = new DateTime();
if(date("Hi") <= $begin && date("Hi") >= $end){
//run code
}
}

Your problem lies here:
if(date("Hi") <= $begin && date("Hi") >= $end){
You are trying to do "greater than" and "less than" comparisons on strings. You should use the integer values (epoch time) then you can do this.
if(time() >= strtotime('14:00') && time() <= strtotime('15:00')) {
echo 'In Range2';
} else {
echo 'out of range2';
}
Note: This is for between 2:00pm and 3:00pm just to show it works (it currently is 2:00pm where I am located).
Demo: https://3v4l.org/NhnfM

Related

Time dependent URL redirection script, should work differently on Monday - How?

This is the top part of a script I am using for redirection.
It connects to two txt based databases depending on time and redirects the user to a particular link.
There are two databases
'db1.txt' and 'db2.txt'
I only want to use the 'db2.txt' on Mondays.
All other day it should work normally, but on Mondays only, it should not change to urls1.txt.
How can I achieve that ?
$time = date("Hi", time());
if ($time >= 2224 && $time <= 2359)
{
$db = "db1.txt";
}
elseif ($time >= 0000 && $time <= 729)
{
$db = "db1.txt";
}
else
{
$db = "db2.txt";
}
Edit:
I am from India, and I am using server time in my script to avoid more complications. The script is designed to load db1.txt from 9:00AM to 6:00PM IST, and db2.txt from 6:01PM to 8:59AM. So using the "if (date('N') !=1 " wont work. I will need to change the time-zone as well.
I think you need to add this condition != monday like this
$time = date("Hi", time());
if (date('N') !=1 && $time >= 2224 && $time <= 2359)
{
$db = "db1.txt";
}
elseif (date('N') !=1 && $time >= 0000 && $time <= 729)
{
$db = "db1.txt";
}
else
{
$db = "db2.txt";
}
note : N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
Check the argument documentation for the date function. With:
date('N');
you should be able to check if it's Monday and execute your desired code conditionally, ex.:
if(date('N') === 1){
}else{
}

Time dependent URL redirection script not working properly

This is the top part of a script I am using for redirection. It connects to two txt based databases depending on time and redirects the user to a particular link. There are two databases 'db1.txt' and 'db2.txt', It should be using only the 'db2.txt' on Sundays.
It should use the 'db1.txt' Monday-Saturday 9AM to 6PM
and
It should use the 'db2.txt' Monday-Saturday 6:01PM to 8:59AM
but now here in India, time is 12.26AM, and it is still using 'db1.txt' instead of 'db2.txt'
How to fix it ?
date_default_timezone_set('Asia/Kolkata');
$time = date("Hi", time());
##
if (date('N') !=7 && $time >= 0900 && $time <= 1800)
{
$db = "db1.txt";
}
else
{
$db = "db2.txt";
}
I believe your leading zeros are messing up the comparison, use this instead:
date_default_timezone_set('Asia/Kolkata');
$time = date("G");
##
if (date('N') !=7 && $time >= 9 && $time < 18)
{
$db = "db1.txt";
}
else
{
$db = "db2.txt";
}

PHP if between 2 dates

I'm working on a plugin, but I can't get it working.
The code below is supposed to do something when the current date is between 2 chosen dates by the user.
So if date is in between 12-01-2016 ($snow['period_past']) and tomorrow is 12-03-2016 ($snow['period_future']), do something...
$date = date('Y-m-d');
$date = date('Y-m-d', strtotime($date));
$snowStart = date('Y-m-d', strtotime($snow['period_past']));
$snowEnd = date('Y-m-d', strtotime($snow['period_future']));
if (($date > $snowStart) && ($date < $snowEnd)) {
// do this and that
}
The code above works, but it only works between the dates. How can I make it work so it also works when its at the $snow['period_past'] date and $snow['period_future'] date?
Sorry for my bad explanation, English is not my native language.
if (($date >= $snowStart) && ($date <= $snowEnd))
{
// do this and that
}
You are doing a greater than > or less than < comparison.
To get the condition to meet when the date is equal to $snow['period_past'] or $snow['period_future'], you should have the following comparison in place:
if (($date >= $snowStart) && ($date =< $snowEnd))
{
// your code here
}

Pulling in data around/after midnight

Ok.. so I've created myself a messy problem.
So I have a jquery slider that shows 5 slides of content
1) -2 hours ago
2) -1 hour ago
3) (0) present
4) +1 hours
5) +2 hours
The content for each slide is decided by what time of day it is. However when it comes to trying to go back/forwards 1 to 2 hours during the run up to midnight and after midnight the whole script breaks, and kills the site.
<?php
$h = date('G', strtotime ("-2 hour")); //set variable $h to the hour of the day.
$m = date('i', strtotime ("-2 hour")); //set variable $m to the min of the hour.
$d = date('w', strtotime ("-2 hour")); //set variable $d to the day of the week.
// SATURDAY SCHEDULE
if ($d == 6 && $h >= 0 && $h < 07) $file ='earlyhours.php';
else if ($d == 6 && $h >= 07 && $h < 09) $file ='breakfast.php';
else if ($d == 6 && $h >= 09 && $h < 12) $file ='throughthemorning.php';
else if ($d == 6 && $h >= 12 && $h < 13) $file ='rewind.php';
else if ($d == 6 && $h >= 13 && $h < 17 && $m <= 30) $file ='nonstop.php';
else if ($d == 6 && $h >= 17 && $m >= 30 && $h <21) $file ='livetrend.php';
else if ($d == 6 && $h >= 17 && $m >= 35 && $h < 21) $file ='nonstop.php';
else if ($d == 6 && $h >= 21 && $h < 18) $file ='gennation.php';
else if ($d == 6 && $h >= 23) $file ='earlyhours.php';
else if ($d == 7 && $h >= 0) $file ='earlyhours.php';
require $_SERVER['DOCUMENT_ROOT'] . '/collection/profiles/' . $file . '';
?>
As you can see it figures the time and then drops the correct file in - there's five of these for everyday of the week (-2.php, -1.php, 0.php, 1.php, 2.php).
Does anybody have a solution? Ideally I need to stop the break, but I don't want my visitors to be scrolling +1 / 2 or -1 / 2 hours on for the same days rotation when it nears, and steps over midnight.
For example, right now the code is broken on -2.php until at least 2am (my timezone) so that it back track.
I've totally burnt myself out trying to figure this one out.
The problems arising from the change of day can become intractable. I'd tackle this a different way. Start by calculating the day and hour for the five periods your interested in and use DateTime to do the heavy lifting. Then, use a function to provide the schedule item for a particular day/time combination.
Here's a skeleton
<?php
date_default_timezone_set('Pacific/Auckland');
$now = new DateTime();
$oneHour = new DateInterval('PT1H');
$minusOne = (clone $now);
$minusOne->sub($oneHour);
$minusTwo = (clone $minusOne);
$minusTwo->sub($oneHour);
$plusOne = (clone $now);
$plusOne->add($oneHour);
$plusTwo = (clone $plusOne);
$plusTwo->add($oneHour);
echo returnFile($minusTwo);
echo returnFile($minusOne);
echo returnFile($now);
echo returnFile($plusOne);
echo returnFile($plusTwo);
function returnFile(DateTime $t) {
$day = $t->format('D');
$hour = $t->format('G');
// echo "Day:$day, Hour: $hour;<br>";
switch ($day) {
case 'Mon':
if ($hour<7) {
// Small hours Monday...
$filename = "smallMonday.html";
break;
}
if ($hour<12) {
// Monday morning
$filename = "morningMonday.html";
break;
}
break;
case 'Tue':
if ($hour >=23) {
// Late Tuesday
$filename = "lateTuesday.html";
}
default:
$filename = "Some other time";
}
return $filename;
}
?>
I haven't put in a complete schedule - you can work that out.
If you're using PHP 5.5 or later you can use DateTimeImmutable instead of DateTime which does away with all the cloning.
There's a fiddle here
Get rid of the leading zeros in your comparisons. Those are octal numbers and not decimals. You won't get the results you expect.
// 09 is not a valid octal number. It gets converted to zero in decimal.
else if ($d == 6 && $h >= 07 && $h < 09)
..
else if ($d == 6 && $h >= 09 && $h < 12) $file ='throughthemorning.php';

Most effective way to determine if a datetime is within a time frame

I have a cronjob, that kicks in every 5 minutes. It should do some tasks only at specific times of the day (e.g. morning and evening).
What's php's most effective / elegant way to determine if the DateTime of now is in between the 5 minute time frame in that the cronjob may kick in?
At the moment I'm doing:
$date = new DateTime();
$hour = (int)$date->format('H');
$min = (int)$date->format('i');
if($hour == 7 && ($min >= 40 || $min < 45)) {
// Do something in the morning
}
if($hour == 21 && ($min >= 00 && $min < 05)) {
// Do something in the evening
}
But this seems like a lot of code. Ain't there something like
$date->isInTimeRane($begin, $end);
as native php code?
You can extend DateTime to add your own methods to it. I would do it this way:-
class MyDateTime extends DateTime
{
/**
* Checks if this DateTime is between two others
* #param DateTime $start
* #param DateTime $end
* #return boolean
*/
public function inRange(DateTime $start, DateTime $end){
return ($this >= $start && $this <= $end);
}
}
Then you can simply do:-
$begin = new DateTime($sometime);
$end = new DateTime($someLaterTime);
$myTime = new MyDateTime($yetAnotherTime);
var_dump($myTime->inRange($begin, $end);
That is the cleanest way I can think of of doing it and pretty much what you asked for.
If $begin and $end are of type DateTime as well, you can simply use them like this:
if ($begin <= $date && $date <= $end) {
// .. date is within the range from $begin -> $end ..
To address your specific problem, how about this (quite elegant) function:
function isWithinTimerange($hours, $minutes, $timerangeInMinutes = 5) {
$now = new DateTime();
$begin = clone $now;
$begin->setTime($hours, $minutes);
$end = clone $begin;
$end->modify('+'. intval($timerangeInMinutes) .' minutes');
return ($begin <= $now && $now < $end);
}
if (isWithinTimerange(7, 40)) {
// ...
You can use the UNIX time instead (seconds since Jan,1,1970 aka Epoch). Then logic should be something like the following.
<?php
$current_time = time(); //Get timestamp
$cron_time = (int) ;// Time cron job runs (you can use strtotime() here)
$five_minutes = 300; //Five minutes are 300 seconds
if($current_time > $cron_time && $current_time - $cron_time >= $five_minutes) {
echo "Cron Job is too late";
} elseif($current_time >= $cron_time && $five_minutes >= $current_time - $cron_time){
echo "Cron Job ran within time frame";
}
?>

Categories