PHP - check if time between 22:00 and 02:00 - php

i have the following code :
$now = date('2018-12-28 23:00:00');
$begintime = new DateTime('22:00');
$endtime = new DateTime('03:00');
if($now >= $endtime && $now <= $begintime){
// not between times
echo "Run";
} else {
// between times
echo "Skip";
}
and the echo is
Skip
because $now is bigger than $begintime that make the output is false
what is the correct way to know if time is not the between the $begintime and $endtime?
I searched all of the relevant issues and I've just wasted 3 days of my life because of this issues, but couldn't find something that even elucidated anything from this forum and google for me. Please help me this issue has already taken an absurd amount of days from my life already and sorry for my english before.. :D

Your code displays enormous amount of misunderstanding of how things are working and it leads to the problem. Please take a look at official documentation, you will see that date() returns string and DateTime is an object. They can't be compared directly, you need to convert them into comparable types beforehand. Also notice that DateTime expects to get a date, not just time. Actually without date being defined your $endtime is actually smaller then $starttime:
$begintime = new DateTime('22:00');
$endtime = new DateTime('03:00');
echo $begintime < $endtime ? 'Yes':'No';
This code snippet will return No.
You need to convert $now to a DateTime and you need to add dates to your start / end time marks. For example:
$now = \DateTime::createFromFormat('Y-m-d H:i:s', '2018-12-28 23:00:00', new \DateTimeZone('UTC'));
I can't provide example of converting start / end time marks because you have not defined how do they actually need to look like.

One solution may be :
$now = "23:00"; // date ('H:i');
$begintime = "22:00";
$endtime = "03:00";
$now_t = DateTime::createFromFormat('H:i', $now);
$begintime_t = DateTime::createFromFormat('H:i', $begintime);
$endtime_t = DateTime::createFromFormat('H:i', $endtime);
if ($now_t > $begintime_t || $now_t < $endtime_t)
{
echo "Skip";
}
else
{
echo "Run";
}

UPDATE
finnaly, i solve my problem..
can someone remove the duplicate tags from my question and find the correct title for this issue? maybe someone who have same issue like me, can search my question and find the answer..
sorry for my english, i still learning..
// this is variable from mysql database
$mysql_start = "2018-12-28 21:45:00"; // its from mysql DATETIME and time show when this script will be run
$begintime = "22:00"; // user can choose when this script stop
$endtime = "20:00"; // user can choose when this script run
$mysql_start = explode(' ', $mysql_start);
$taskdays = $mysql_start[0]; // 2018-12-28
echo $taskhours = $mysql_start[1]; // 21:45:00
echo "<br>";
$taskhours = explode(':',$taskhours);
$taskhours = $taskhours[0]; // 22
echo $begintime = date($begintime);
echo "<br>";
$begintime = explode(':',$begintime);
$begintime = $begintime[0]; // 20
echo "<br>";
echo $endtime = date($endtime);
echo "<br>";
$endtime = explode(':',$endtime);
$endtime = $endtime[0] - 1; // because if endtime is 6, so if its 05:59, the endtime will be end on 05
echo $endtime = str_pad($endtime, 2, '0', STR_PAD_LEFT); // if 6, it will add 0 so it will be 06
echo "<br>";
$jamarray = array("00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23");
$ray = array();
if ($begintime > $endtime){
echo '$begintime is bigger than $endtime<br>';
foreach($jamarray as $ray) {
if($ray >= $begintime or $ray <= $endtime){
//echo '<br>';
//print_r($ray);
$eray[] = $ray;
}
}
$aslinya = array_diff($jamarray,$eray);
print_r($aslinya);
if (in_array($taskhours, $aslinya))
{
echo " <= script run in this time";
}
}else{
echo '$begintime is less than $endtime<br>';
foreach($jamarray as $ray) {
if($ray >= $begintime and $ray <= $endtime){
//echo '<br>';
//print_r($ray);
$eray[] = $ray;
}
}
$aslinya = array_diff($jamarray,$eray);
print_r($aslinya);
if (in_array($taskhours, $aslinya))
{
echo " <= script run in this time";
}
}

Related

Compare two hours inside while loop [duplicate]

This question already has answers here:
Print time in 15-minute increments between two times in the same day
(10 answers)
Closed 11 months ago.
I'm trying to echo list of hours.
<?php
$startTime = "9:00:00";
$endTime = "19:00:00";
$st = strtotime($startTime);
$et = strtotime($endTime);
while ($st < $et) {
echo $st = date( "H:i", strtotime('+30 minutes', $st) );
echo '<br>';
}
?>
Inside that list, users will choose their reservation hour. But my while loop works like infinite loop.
Just like the previous answer, you're messing with data types while doing arithmetic.
PHP ships with built-in date time arithmetic through date and time API.
Your code could look much more clear and elegant and less error prone (no strtotime(), conversion, etc)
You could do something like this instead:
<?php
$startTime = DateTime::createFromFormat('H:i:s', '9:00:00');
$endTime = DateTimeImmutable::createFromFormat('H:i:s', '19:00:00');
$interval = new DateInterval('PT30M'); // 30 minutes
$reservation = [];
while ($startTime <= $endTime) {
$reservation[] = $startTime->format('H:i');
$startTime->add($interval);
}
echo join(PHP_EOL, $reservation) . PHP_EOL;
Links:
Date/Time Arithmetic
You're converting $st from a integer (timestamp) with strtotime() to a string with date() so your loop keeps going since while (string < integer)... is always true.
You can do this instead:
while ($st < $et) {
$st += (30 * 60); // Add 30 minutes in seconds
echo date("H:i", $st);
echo '<br>';
}

how to check if time is more than 30minute?

I have saved a time. I would like to check whether the saved time is 30 minutes greater than the current time. You can see in the code what I have done so far but it doesn't work.
I would need some help fixing that code.
$current = "08:05";
$to_check = date('h:i');
if($to_check > $current + strtotime('30 minute')){
echo "greater";
}
else {
echo "not greater";
}
First, your $current isn't the current time, $to_check is, so your variable names are misleading.
That being said, store your "08:05" as a Unix timestamp then see if the difference between the two is greater than 30 * 60.
$seconds = 1800; // 30 mins
$time1 = strtotime($db_time) + $seconds;
if(time() >= $time1)
echo "Time's up!"
else
echo "time has not expired";
This should work for you:
<?php
$current = date('H:i');
$to_check = date('H:i', strtotime('+30 minutes'));
$to_check = date('H:i', strtotime($record['date'])); //If value is from DB
if($to_check > $current){
echo "greater";
}
else {
echo "not greater";
}
Save time using time function this would give you time in seconds from 1970 so for example current time is 1501137539 and after 30 minutes it would be (1501137539 + 30*60) so you would just need to check if difference b/w current time and stored time is greater that 30*60 then half an hour is over.
Try this snippet:
function x_seconds($to_check = 'YYYY-mm-dd H:i:s') {
$to_check = strtotime($to_check);
$current = time() + 1800; //We add 1800 seconds because it equals to 30 minutes
return ($current>=$to_check) ? true : false;
}
Or go pro, and have a custom "seconds since", just because you can?
function x_seconds($to_check = 'YYYY-mm-dd H:i:s', $seconds = 1800) {
$to_check = strtotime($to_check);
$current = time() + $seconds; //We add x seconds
return ($current>=$to_check) ? true : false;
}
Example usage:
$date = date('Y-m-d H:i:s', '2017-07-27 05:00');
if(x_seconds($date)):
print "Is within 30 minutes.";
else:
print "IS NOT within 30 minutes";
endif;
Try this to solve the issue
$current = strtotime('12:00:00');
$to_check = strtotime(date('H:i:s'));
$newtime = round(( $to_check - $current ) /60 );
if($newtime > 30){
echo "greater";
}else {
echo "not greater";
}

Simulate "do not disturb" functionality in PHP

I want to check between two user-specified times everyday and not run some function call (i.e. "Do Not Disturb").
For example, a user set a "Do Not Disturb" time block between 10:00pm to 6:00am (next day).
FYI, no days/dates are being specified by the end-user, ONLY times. This will run consistently everyday, 7 days a week.
So between 10pm-6am (next day), any function call is ignored. This is what I've written up so far:
$now = time(); // or $now = strtotime('11:00pm'); to simulate time to test
$start = strtotime('10:00pm');
$end = strtotime('6:00am +1 day');
// alternative time block
//$start = strtotime('10:00am');
//$end = strtotime('11:00am');
//debug
//echo date('r', $now) . '<br>' . date('r', $start) . '<br>' . date('r', $end) . '<br><br>';
if($start > $now || $now > $end) {
echo 'disturb';
} else {
echo 'do not disturb';
}
But this doesn't seem to work, because once you reach midnight, it's a new day, but the $end variable is already a day ahead.
I tried putting it a day behind, but then the issue is that the value of $end ends up being lower than the value of $start, which isn't correct.
I also tried adding a day to the $now variable whenever the time reaches midnight, but the issue w/ that is, what if the $start and $end times are within the same day?
What am I missing here?
Apparently you're trying to build some kind of calendar functionality here.
If you use strtotime('10:00pm'); this will change to the timestamp of the next day after midnight.
So you need to give the variable a date
$start = strtotime('2015-02-26 10:00pm');
$end = strtotime('2015-02-27 6:00am');
Not sure how you store these time blocks, but ideally they would be stored in a database table.
If it's every day the same you could do:
$now = time(); // or $now = strtotime('11:00pm'); to simulate time to test
$start = strtotime('10:00pm');
$end = strtotime('6:00am'); // without the +1 day
if($start > $end) {
if($start > $now && $now > $end) {
echo 'disturb';
} else {
echo 'do not disturb';
}
}else{
if($now < $start || $now > $end) {
echo 'disturb';
} else {
echo 'do not disturb';
}
}
That's a nice question actually,
You can use the the relatively new object oriented way of dealing with times.
I'll link you some info as I don't have time to write an entire example
http://php.net/manual/en/datetime.diff.php
http://php.net/manual/en/class.datetime.php
http://php.net/manual/en/class.dateinterval.php
specifically from the docs :
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Hope it helps
I would convert to DateTime() objects instead. Then you won't get any issues with days ending.
// obviously you'll need to feed in the date as well so
// that might involve some refactoring
$now = new DateTime();
$start = new DateTime('2015-02-26 10:00');
$end = new DateTime('2015-02-27 06:00');
Now you can compare as before.
If you don't know the date and your users are only specifying time, you might need to add the date dynamically. These are just for example.
Edit: to cope with unknown days, you could dynamically generate after grabbing today:
$today = new DateTime();
$start = new DateTime($today->format('Y-m-d') . ' 10:00');
$end = new DateTime($today->format('Y-m-d') . ' 06:00');
$end->add(new DateInterval('P1D'));

PHP Time loop between start time and end time

I have this function that gives me a set of options in a select input.
The options give me times with 5 minute interval.
The problem is when the time is like 23:45, the options will start from 00:10 and loops based on the $j variable.
This is what I want to do in words:
Give me a list of options in 5 minutes interval from $open_time till $close_time.
If the current Time ($timeNow) is greater than the $open_time, set the $open_time to the $timeNow to be shown as first option.
Do this loop only until the $close_time.
I hope this is clear.
Appreciate your help :)
Here is the code:
function selectTimesofDay(){
$output = "";
$now = date('G:i ', time()); // time now
$timeNow = strtotime($now); // strtotime now
$next_five = ceil($timeNow / 300) * 300; // get next 5 minute
// time now rounded to next 10 minute
$round5minNow = date('G:i', strtotime('+15 minutes',$next_five));
$open_time = strtotime('17:00');
$close_time = strtotime('23:59');
// in the middle of working hours, time sets to current
if($timeNow >= $open_time && $timeNow < $close_time){
$open_time = strtotime($round5minNow);
}
$time_diff = round(($close_time - $open_time)/60) ;
if(date('l') == 'Friday'){
$j = ($time_diff/5)+11; // working hours extended untill 1:00 AM
} else{
$j = ($time_diff/5)-1; // working hours untill 12:00 AM
}
for($i = 0; $i <= $j; $i++){
$b = $i*5;
$data = date('l')." - ".date("H:i", strtotime('+'.$b.' minutes', $open_time));
$output .= "<option value=\"{$data}\">";
$output .= $data;
$output .= "</option>";
}
return $output;
}
What you really need is:
function selectTimesOfDay() {
$open_time = strtotime("17:00");
$close_time = strtotime("23:59");
$now = time();
$output = "";
for( $i=$open_time; $i<$close_time; $i+=300) {
if( $i < $now) continue;
$output .= "<option>".date("l - H:i",$i)."</option>";
}
return $output;
}
So what this does is run a loop checking every five-minute interval between opening and closing. Skip it if it is before the curent time, and otherwise add an option.
It's much more efficient than what you were trying to do, and probably easier to understand too.
You can even put this after the loop:
if( $output == "") return "<option disabled>Sorry, we're closed for today</option>";
Also, notice how I left out the value attribute all the time. That's because in the absence of a value, the option's text is used as a value. Thus this solution avoids needless duplication.
Consider taking the hard-coded open and close times out of the function body. The goal with functions is to write code that you can reuse, so if your hours change then you don't have to change with your function, but rather the arguments that are passed to it.
// sample usage: print '<select>'.selectTimesofDay('17:00', '23:59').'</select>';
function selectTimesofDay($start=false, $end=false, $interval='5 minutes'){
$interval = DateInterval::createFromDateString($interval);
$rounding_interval = $interval->i * 60;
$date = new DateTime(
date('Y-m-d H:i', round(strtotime($start) / $rounding_interval) * $rounding_interval)
);
$end = new DateTime(
date('Y-m-d H:i', round(strtotime($end) / $rounding_interval) * $rounding_interval)
);
$opts = array();
while ($date < $end) {
if ($date->getTimestamp() < time()) {
$date->add($interval);
continue;
}
$data = $date->format('l').' - '.$date->format('H:i');
//$opts[] = '<option value="'.$date->getTimestamp().'">'.$data.'</option>'; // < -- pass the timestamp instead of a string?
$opts[] = '<option>'.$data.'</option>';
$date->add($interval);
}
return count($opts) < 1 ?
'<option value="-1">- closed -</option>' :
implode("\n", $opts);
}
Documentation
PHP's DateTime object - http://www.php.net/manual/en/class.datetime.php
PHP's DateInterval object - http://www.php.net/manual/en/dateinterval.format.php
PHP functions - http://www.php.net/manual/en/functions.user-defined.php
PHP function tutorial - http://www.tizag.com/phpT/phpfunctions.php

Fill Out The Gaps Between Two Times With PHP

I've got to write a loop that should start and end between two times. I know there are many ways to skin this cat, but I'd like to see a real programmers approach to this function.
Essentially I have Wednesday, for instance, that opens at 6:00pm and closes at 10:30pm.
I'm looking to write a loop that will give me a table with all of the times in between those two in 15 minute intervals.
So, I basically want to build a one column table where each row is
6:00pm
6:15pm
7:15pm
etc...
My two variables to feed this function will be the open time and the close time.
Now don't accuse me of "write my code for me" posting. I'll happily give you my hacked solution on request, I'd just like to see how someone with real experience would create this function.
Thanks :)
$start = new DateTime("2011-08-18 18:00:00");
$end = new DateTime("2011-08-18 22:30:00");
$current = clone $start;
while ($current <= $end) {
echo $current->format("g:ia"), "\n";
$current->modify("+15 minutes");
}
Try it on Codepad: http://codepad.org/JwBDOQQE
PHP 5.3 introduced a class precisely for this purpose, DatePeriod.
$start = new DateTime("6:00pm");
$end = new DateTime("10:30pm");
$interval = new DateInterval('PT15M');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $time) {
echo $time->format('g:ia'), PHP_EOL;
}
echo $end->format('g:ia'); // end time is not part of the period
$start = strtotime('2011-08-11 18:00:00');
for ($i = 0; $i < 20; $i++) {
echo date('g:ia', $start + ($i * (15 * 60))), '<br>';
}
I would go with the DateTime functions and increase the time by 15 minutes every loop-turn as long as the current time is lower then the end-time.
EDIT: as user576875 has posted
$start_date = '2019-07-30 08:00:00';
$end_date = '2019-09-31 08:00:00';
while (strtotime($start_date) <= strtotime($end_date)) {
echo "$start_date<br>";
$start_date = date ("Y-m-d H:i:s", strtotime("+1 hours", strtotime($start_date)));
}

Categories