Creating a conditional function based on timeframe - php

As the title suggests, I need to create a conditional function in PHP based on time frame. I am very basic when it comes to knowledge of PHP but can understand concepts.
I have some 3rd party code but I need it to function only between a certain time range and to be essentially disabled when out of range.
I am trying to achieve something as follows:
IF time >=0800<=1700 (
DO NOTHING
) ELSE (
RUN CODE
)
The backstory for the question is I have some 3rd party code to integrate googles dialogflow into a website but it currently runs 24/7, I have a livechat system running from 0800 until 1700 and want googles diaglogflow (chatbot) to run when the livechat isn't running.
I'm not really looking for a straight up answer, but more of the concept behind how I can achieve this so I can better learn for the future.
Thanks,
Martyn

IF time >=0800<=1700 (
DO NOTHING
) ELSE (
RUN CODE
)
First things first, you don't need if else, else alone is fine, in pseudocode:
IF time < 0800 OR TIME > 1700
RUN CODE
Next thing to know will be how to check current time, there's plenty of way to do it so lets think which way will be the best.
We only care about hours and minutes, so lets take them.
$hourNow = date('H'); // $hour now is a string but we'd rather have it as an integer for better comparison.
$hourNow = (int) $hourNow; // this will cast, for example "15" to 15
$minuteNow = (int) date('i'); // as you can see you can do casting and getting a minute value at once
Now when we have all the info we need, it should be easy to write:
if ($hourNow < 8 || ($hourNow === 17 && $minuteNow > 0) || $hourNow > 17) {
// Do whatever you need in this case.
}
The conditional is pretty simple: if hour is less than 8 - we know it's prior to 8 o'clock.
If it's > 17 it's obviously later.
And if it's 17, it's kind of an edge case, as it could be 17:00 - so we need to specify that the minute is greater than 0.
I hope that helps, feel free to ask if something's not clear.

Related

Trying to check for time above 9am in php but wont take any thing above 10?

I'm simply trying to check if the time is either above 9am or below 6pm, the 6pm check works fine and displays the data where as 9am one does nothing but works when changed to 10am.
Here is the line of code I'm using
elseif ((($data[6]) < "09:00") || (($data[6]) > "18:00"))
{
$contact[] = $data;
}
So, let us assume that your time format is always hh:mm. You want to check if the time is between 9 and 18 hours. The problem in your code, as you described, comes when you are check again 09:mm. As it strips away the minute part and just compares the hours.
I would try something like this:
elseif ( implode("", explode(":", $data[6])) > 900 && implode("", explode(":", $data[6])) < 1800)
I will explain the approach step by step.
First of all, this code checks if the date is within the range of 09:00 to 18:00. The code you have provided tested if it is less than 9 or more than 18.
Let us focus on one part of the code, that will explain the whole thing as well:
implode("", explode(":", $data[6])) > 900
First, we separate hours and minutes using the explode function. This gives us an array with two values.
`[0] => hh,`
`[1] => mm`
Now that we have separated this value we implode or concatenate them using the implode function that has no separator.
Next, instead of testing against the string, we test against the number. 09:00 is the same as 900 in this case.
Thus, we can check if the time is within the required limits.

PHP check if current time is between two times

I have a start and end time in milliseconds.
I have to get all the TV series that are ON AIR when the user visits the page.
So I am trying to do this:
if($prog["inizio"] < time() && $prog["fine"] > time()){
array_push($programmazioneFinal[$date."-".$prog["id_canale"]], $prog);
}
The logic is to get only those series whose starting time is lower than now (the serie is already started) and the end time is bigger than now.
For some reasons it is also returning those series that start much later in the day, not just the ones ON AIR now.
What's wrong?
I have added a screenshot of my DB just to make this clearer.
Thank you!
In PHP: You can use strtotime. This will give you timestamp value which you can use for comparison
strtotime("now")
Edit in your code
if($prog["inizio"] < strtotime("now") && $prog["fine"] > strtotime("now")){
array_push($programmazioneFinal[$date."-".$prog["id_canale"]], $prog);
}
Make your query look like
Select * from ... WHERE UNIX_TIME($your_date_parameter) BETWEEN inizio AND fine

"Half Hour" Intervals for date Method

This seems like a basic question and I don't see if it has been asked before:
I have this if statement in a script:
if (date('H') < $loc_item -> closing) {
Basically it's a script for business. And it has to do with when a store closes. 6 o'clock, 7 o'clock, etc.
The variable uses values 1 - 24 for hour only. However, SOME business close at, 5:30 PM (17:30), 6:30 PM (18:30),
Would a value of 18.5 represent 6:30 PM? If not, what is the simplest way to enter use the date function where I can add a value of 1830 and it knows I mean 6:30PM?
Edit: There is NO user output here. The script just needs to know to throw a "switch" at a certain time of day.
You could use strtotime()
date("Hi", strtotime("18:40"));
If you want the date function to return hours and minutes, then date('H') isn't going to do it for you. You need date('Hi'). That returns a string. The following is a complete code snippet:
<?php
date_default_timezone_set('America/New_York');
echo "The time is ".date('Hi')."\n";
$closingTime = "12:15";
echo "The store closes at ".$closingTime."\n";
if (strtotime(date('Hi')) < strtotime($closingTime)) echo "it is still open\n";
else echo "the store is closed\n";
?>
Sample output:
The time is 1225
The store closes at 12:15
the store is closed
You aren't really giving us enough information to answer the question.
First off, you might as well make your script support all minutes...cause some stores might close # 6:45.
I think the solution you are looking for is to simply do a comparision of timestamps.
The easiest way to do this is using strtotime.
I would tend to do something like:
$now = new DateTime();
$closing = new DateTime('19:30');
if ($now < $closing) // not closed
I assume you don't have to worry about stores closing in the early AM.

Split a time range into pieces by other time ranges

I have a complicated task that I have been beating my head against the wall now for a few days. I've tried about 4 different approaches, however each seems to stall and it is becoming extremely frustrating.
I have a time range. For example, 14:30:00 until 18:30:00. Consider this time range somebody's work shift. During this time range, they state they cannot work from 15:30:00 until 16:30:00 and from 17:30:00 until 18:30:00. I need to modify the original shift's start and end times to remove the conflicting shifts.
The original shift array looks like this:
$original_shift[0]['start'] = '14:30:00';
$original_shift[0]['end'] = '18:30:00';
And the time ranges to be removed from the original shift look like this:
$subshift[0]['start'] = '15:30:00';
$subshift[0]['end'] = '16:30:00';
$subshift[1]['start'] = '17:30:00';
$subshift[1]['end'] = '18:30:00';
Here is a visualization:
So, I basically need my original shift to look like this when I'm done:
$original_shift[0]['start'] = '14:30:00';
$original_shift[0]['end'] = '15:30:00';
$original_shift[1]['start'] = '16:30:00';
$original_shift[1]['end'] = '17:30:00';
Some complications that I also need to consider are:
These time ranges may be any times (not constrained to the half hour as I have used in my example), however I will know with 100% certainty the the unavailable time ranges will always start and end on or in between the original shift's start and end times.
Unavailable times may butt up and/or take the entire original shift's time up.
I'm not looking for someone to "write my code" as much as I am looking for someone who has dealt with something like this in the past and may have some insight on how they accomplished it.
As you specifically asked for "some insight" rather than a full working answer, I'd personally go with arrays populated with "minutes".
$shift = array(
'start' => '15:30:00',
'end' => '18:30:00',
'original' => array(),
'unavailable' => array(),
'modified' => array()
);
You'd then do some jiggery pokery to convert 15:30:00 into 930 and 18:30:00 into 1110 (number of minutes) which will give you the difference between start and end times.
Use range() to quickly fill up the original array, load in your unavailable in a similar format and then use things like array_intersect() and array_diff() to work out which minutes from the original shift are unavailable.
From that, build up the modified array, and read directly from there to your output.
You need to do calculations of time-ranges. As the image shows this seems like a simple subtraction. It would be nice to just have objects that do these.
I had no code for this ready, so the following concept is a bit rough although probably not that bad.
A Range type that represents a time from-to. Those are as DateTime so that the benefits of these existing types can be used. I didn't use much of the benefits so far, however for the rest of the application this can make sense.
The Range type already contains some basic comparison methods I thought were useful to do parts of the calculations.
However as an object can not divide itself into two I also created a Ranges type which can represent one or more Ranges. This was necessary to have something that can be "divided".
I cheated a little here because I implemented the difference calculation as a member of Range, returning an array with one or multiple Range objects. The final calculation then is just having a shift and substract the unavailable ranges from it:
$shift = new Ranges(new DateTime('14:30:00'), new DateTime('18:30:00'));
$unavailables = new Ranges([
new Range(new DateTime('15:30:00'), new DateTime('16:30:00')),
new Range(new DateTime('17:30:00'), new DateTime('18:30:00')),
]);
$shift->subtract($unavailables);
The shift then spans:
14:30:00 - 15:30:00
16:30:00 - 17:30:00
Demo; Gist
I can not say if it is worth the abstraction, what is nice with DateTime objects is that you can compare them with >, < and =. The real benefit from these classes might shed into light when you need more calculations between Range and Ranges. Maybe the interface is not sweet yet, however the basic calculations behind are outlined in the code already.
One caveat: The difference between 14:00-15:00 and 14:00-15:00 in my code will result to 14:00-14:00. I keep the start time to not run empty, but you can run empty, too. The Ranges object should handle it nicely.
The code should speak for itself:
$original_shift[0]['start'] = '14:30:00';
$original_shift[0]['end'] = '18:30:00';
$breaks[0]['start'] = '14:30:00';
$breaks[0]['end'] = '15:30:00';
$breaks[1]['start'] = '16:30:00';
$breaks[1]['end'] = '17:30:00';
$modified_shift = array(
array('start' => $original_shift[0]['start'])
);
for($x = 0, $y = count($breaks), $z = 0; $x < $y; $x++){
$modified_shift[$z]['end'] = $breaks[$x]['start'];
if($modified_shift[$z]['end'] != $modified_shift[$z]['start']){
$z++;
}
$modified_shift[$z]['start'] = $breaks[$x]['end'];
}
$modified_shift[$z]['end'] = $original_shift[0]['end'];
if($modified_shift[$z]['end'] == $modified_shift[$z]['start']){
unset($modified_shift[$z]);
}

checking a list of timestamps are between 12 and 1 in the day

I have a list of timestamps that represent a list of backed up files. But to reduce the amount of space needed I only want to keep the files that are from around mid day- I have started writing a function check but got stuck on how could i check if the timestamp is between 12 and 1 for that day? I have a list of timestamps for many days.
function check_date($timestamp='')
{
if (($timestamp < strtotime("-1 week")) && (time is between 12 and 1 )){
}
else
remove
}
I wrote an answer to this previously, I will try find a link in a minute when im free but essentially get the timestamp for 12 and the timestamp for 1 then
if(timestamp12 < curTimestamp && curTimestamp < timeStamp1)
Then you know that the curTimeStamp is between 12 and 1.
Previous answer https://stackoverflow.com/a/11578345/1475461
The other question was for a javascript implentation but timestamp comparison works the same whether you are using PHP, javascript etc. since they are miliseconds/seconds since a set point in time (1st January 1970), so it is just a comparison of integers.
Okay, let me think...ah, here it is. Good old 'localtime' function.
http://www.php.net/manual/de/function.localtime.php
Run your timestamp through this function, then you can check the result.
$TimeInfo = localtime(timestamp, true);
if (($timestamp < strtotime("-1 week")) && $TimeInfo["tm_hour"] == 12) {
}
else remove
With this code, all files, which have arrived at 12:00, up to 12:59 (1 is excluded in this example) are preserved, the others get removed.

Categories