Code start and end in specific time - php

Hi guys i have a code that start and end in specific time, my code is work fine but i want to use this code in data that loop
for example i'll pot names in loop and i want for each one to start and end in specific time:
this is my code:
<?php
date_default_timezone_set('America/New_York');
$time = date('Y:m:d H:i:s');
$timestart = date('Y:m:d H:i:s'); //time start
$timeend = '2016:11:17 10:56:00'; //time end
if($time >= $timeend){
echo "time end";
}else{
echo 'untel end time';
}
$now = new DateTime();
$future_date = new DateTime($timeend);
$interval = $future_date->diff($now);
?>
and i want to know how to use it with loop data?
thanks.

You can use EV or Event extension or implement by loop. I prefer EV extension to this task
And create timer for example:
// Required create variable!
$w = new EvTimer($needWorkedSeconds, $repeatAfterSecond, function ($w) {
echo "iteration = ", Ev::iteration(), PHP_EOL;
});
// Loop until Ev::stop() is called or all of watchers stop
Ev::run();
More read here!
OR use event (but i prefer event to work with socket):
$base = new \EventBase();
$e = \Event::timer($base, function($n) use (&$e) {
echo "$n seconds elapsed\n";
if($isTimeEndNow)
{
$e->delTimer();
}
}, $repeatAfterSecond);
$e->addTimer($repeatAfterSecond);
$base->loop();
More read here!
Or you can try while, for example:
while(true)
{
if($isTimeEndNow)
{
break;
}
sleep($repeatAfterSecond);
}
In example i use undeclareted variable:
$repeatAfterSecond - seconds to next iteration or next call
$isTimeEndNow - this is: time() > $endTimestamp
$needWorkedSeconds - this is seconds: time_start - time_end
ATTENTIONAL!!! Be Careful! I think you make mistake, if you want use MySQL and if you need die script in concrete time. Review your algorithm!!!

Related

PHP add time duration in while loop

I am calculating time duration in while loop by difference of login time and logout time. I want to add all the time duration in a variable and print it out.
The code for this I am using is -
$totaltimespent = new DateTime;
$totaltimespent->setTime(0, 0);
$timespent= (strtotime($totaltimespent->format("H:i:s")));
while ($row = mysqli_fetch_array($result)) {
echo $row['timeoflogin'];
echo $row['logouttime'];
$startTime = new DateTime($row['timeoflogin']);
$endTime = new DateTime($row['logouttime']);
$duration = $startTime->diff($endTime);
echo $duration->format("%H:%I:%S");
$converttime= (strtotime($duration->format("%H:%I:%S")));
$timespent = date("H:i:s",$converttime+$timespent);
}
echo $timespent;
The timeoflogin and logouttime are in format - 05:03:53pm. The $duration is giving right result. I want to add this all duration in varaible and print after while loop. Please help me out.
You can simply add the difference you already calculated inside the loop to another DateTime object and get the final difference between them.
$totalStart = new DateTime('today'); // this will create it with time 00:00:00
$totalEnd = new DateTime('today'); // we will use this to add the intervals from the loop
while ($row = mysqli_fetch_array($result)) {
...
$startTime = new DateTime($row['timeoflogin']);
$endTime = new DateTime($row['logouttime']);
$duration = $startTime->diff($endTime);
$totalEnd->add($duration);
...
}
$totalTimeSpent = $totalStart->diff($totalEnd);
Now all you need to do is format it the way you want to.

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'));

How can I check to see if a request is being made between certain hours on specific days?

I'd like to write a function that returns a boolean true if the request is being made between 8am and 5pm central timw monday-saturday, and false any other time. I know that I will probably be using date() and strtotime()but outside of that, I'm lost. Any pointers?
desired result
if (DuringBusinessHours()) {
// execute this
} else {
// execute this
}
I would suggest something like this:
// create start and end date time
$start = new DateTime('8:00am');
$end = new DateTime('5:00pm');
// get the current time
$now = new DateTime();
// note that you can use the < > operators
// to compare date time objects
if($now >= $start && $now < $end) {
echo 'during business hours';
}

Calculate elapsed time in php

Hi All I'm trying to calculate elapsed time in php. The problem is not in php, it's with my mathematical skills. For instance:
Time In: 11:35:20 (hh:mm:ss), now say the current time is: 12:00:45 (hh:mm:ss) then the time difference in my formula gives the output: 1:-34:25. It should actually be: 25:25
$d1=getdate();
$hournew=$d1['hours'];
$minnew=$d1['minutes'];
$secnew=$d1['seconds'];
$hourin = $_SESSION['h'];
$secin = $_SESSION['s'];
$minin = $_SESSION['m'];
$h1=$hournew-$hourin;
$s1=$secnew-$secin;
$m1=$minnew-$minin;
if($s1<0) {
$s1+=60; }
if($s1>=(60-$secin)) {
$m1--; }
if($m1<0) {
$m1++; }
echo $h1 . ":" . $m1 . ":" . $s1;
Any help please?
EDIT
Sorry I probably had to add that the page refreshes every second to display the new elapsed time so I have to use my method above. My apologies for not explaining correctly.
This will give you the number of seconds between start and end.
<?php
// microtime(true) returns the unix timestamp plus milliseconds as a float
$starttime = microtime(true);
/* do stuff here */
$endtime = microtime(true);
$timediff = $endtime - $starttime;
?>
To display it clock-style afterwards, you'd do something like this:
<?php
// pass in the number of seconds elapsed to get hours:minutes:seconds returned
function secondsToTime($s)
{
$h = floor($s / 3600);
$s -= $h * 3600;
$m = floor($s / 60);
$s -= $m * 60;
return $h.':'.sprintf('%02d', $m).':'.sprintf('%02d', $s);
}
?>
If you don't want to display the numbers after the decimal, just add round($s); to the beginning of the secondsToTime() function.
Using PHP >= 5.3 you could use DateTime and its method DateTime::diff(), which returns a DateInterval object:
$first = new DateTime( '11:35:20' );
$second = new DateTime( '12:00:45' );
$diff = $first->diff( $second );
echo $diff->format( '%H:%I:%S' ); // -> 00:25:25
Keep track of your time using the 'time()' function.
You can later convert 'time()' to other formats.
$_SESSION['start_time'] = time();
$end_time = time();
$end_time - $_SESSION['start_time'] = 65 seconds (divide by 60 to get minutes)
And then you can compare that to another value later on.
Use microtime if you need millisecond detail.
You can implement the solutions shown, but I'm fond of using the phptimer class (or others, this wheel has been invented a few times). The advantage is that you can usually define the timer to be active or not, thereby permitting you to leave the timer calls in your code for later reference without re-keying all the time points.
For high resolution time, try using monotonic clock: hrtime
<?php
$time = -hrtime(true);
sleep(5);
$end = sprintf('%f', $time += hrtime(true));
?>
Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

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