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.
Related
I'm working on a tick based space game http://ricarion.com/ but the ticks only run between certain hours.
08:00-16:30 - run every 30 minutes via a cron job. In the nav bar at the top I want to add "Next Tick: 08:30 06/02/20" for example.
So I was thinking of creating an array:
$tick_times[] = array();
$tick_times[] = 08:00;
$tick_times[] = 08:30;
$tick_times[] = 09:00;
...
$tick_times[] = 16:30;
And then this is where I get stuck, how do I check the existing time, and then compare that against the array selecting the next future time? i.e. It's now 08:34, so the return should be 09:00?
Did you need an array or just want to calculate the next 30-minute interval?
If so this may be similar to:
Round minute down to nearest quarter hour
You do modulo division of 1800 seconds on the current time and add the answer (time remainder of time to the next interval) to the then-current time to get the next event.
<?php
$current_date = date('d-M-Y g:i:s A');
echo $current_date."\n";
$current_time = strtotime($current_date);
$frac = 1800;
$r = $current_time % $frac;
$new_time = $current_time + ($frac-$r);
$new_date = date('d-M-Y g:i:s A', $new_time);
echo $new_date."\n";
http://codepad.org/xs9lMCRQ
Get the now time format it and compare it. In your case you maybe format your $tick_time to the same format like current time.
$date = new DateTime('now');
$date = $date->format('Y-m-d H:i:s');
foreach ($tick_times as $tick_time) {
$date_added = new DateTime($tick_time);
if (strtotime($date_added) == strtotime($date)) {
//do your stuff here
}
}
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!!!
trying to make a simple countdown timer in PHP based on some input from a database which will tweak the end time slightly (with a constant base). However it seems to keep throwing up really strange numbers in the countdowns. I pretty much guarantee my math is wrong somewhere.
PHP
$timeUntil = 10; // for tweaking time remaining (days), this will be dynamic in actual program but will always be an integer
$timeStamp = 1445438099; // timestamp of roughly 2 months in the future
$zUnixDays = $timeUntil * 86400; // converting integer (days) into seconds
$zFinalTime = $timeStamp - $zUnixDays; //tweaking the constant time with the variable time
$remaining = $zFinalTime - time(); // seconds remaining from the future time til now
$seconds_remaining = $remaining%60;
$minutes_remaining = floor(($remaining%3600)/60);
$hours_remaining = floor(($remaining%86400)/3600);
$days_remaining = floor(($remaining%2592000)/86400);
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo json_encode($zTimeCombined);
JS
var result = JSON.parse(results);
var zDays = result[0];
var zHours = result[1];
var zMinutes = result[2];
var zSeconds = result[3];
this should return around 50 days remaining (2 months - 10 days.. very rough) but instead returns 21 days. Any ideas anyone?
Use DateTime instead, it's much easier:
$future = new DateTime();
$future->setTimestamp(1445438099); // passing in to constructor directly is wonky
$start = $future->sub(new DateInterval('P10D'));
$diff = $start->diff(new DateTime());
$interval = $diff->format('%y:%m:%d:%h:%i:%s');
// 0:1:20:23:29:45
list($year, $month, $day, $hour, $minute, $second) = explode(':', $interval);
<?php
$daysToFuture = 10;
// 10 Days in Future
$futureTs = mktime(0,0,0,date("n"),date("j")+$daysToFuture,date("Y"));
// remaining till now ...
$remaining = $futureTs-time();
// in Days
$days_remaining = date("d",$remaining);
echo "<pre>"; print_r($days_remaining); echo "</pre>";
// in hours
$hours_remaining = date("H",$remaining);
echo "<pre>"; print_r($hours_remaining); echo "</pre>";
// in minutes
$minutes_remaining = date("i",$remaining);
echo "<pre>"; print_r($minutes_remaining); echo "</pre>";
// in seconds
$seconds_remaining = date("s",$remaining);
echo "<pre>"; print_r($seconds_remaining); echo "</pre>";
// Array
$zTimeCombined = array($days_remaining, $hours_remaining, $minutes_remaining, $seconds_remaining);
echo "<pre>"; print_r($zTimeCombined); echo "</pre>";
I recommend you to use the DateTime and DateInterval objects
$dateTime = new DateTime();
$dateTime->setTimestamp(1445438099);
$timeInTheFuture = $dateTime->modify('-10 days');
$dateInterval = $timeInTheFuture->diff(new DateTime());
echo json_encode(explode(' ', $dateInterval->format('%d %h %i %s')));
Is it possible to edit variables from a PHP file with the use of Cronjob? If so, how would I go about doing this?
Basically I have a PHP file that looks like this:
<?php
$daynumber = "1";
$txid = tx1;
$endtime = "2014-3-28 20:30:00 GMT+11:00";
?>
What I want is that every 24 hours it changes it by increasing the day number by one and the txid by one.
So basicaly after the cron job running 24 hours after the code above it will look like this:
<?php
$daynumber = "2";
$txid = tx2;
$endtime = "2014-3-29 20:30:00 GMT+11:00";
?>
Is it possible to do? If not, what other way could I produce the same result.
Thank you very much, I appreciate any help I receive.
Forget about cron for this task
Even without the database - if for some reason you don't want to use it:
<?php
define("FIRST_DAY_STRING", "2014-3-26");
define("SHIFT_DAYS", 'P2D');
define("TIME_SUFFIX", " 20:30:00 GMT+11:00");
$today = new DateTime();
$first_day = new DateTime(FIRST_DAY_STRING);
$interval = $first_day->diff($today);
$days = $interval->format('%R%a days');
$end_date = $today->add(new DateInterval(SHIFT_DAYS));
$day_number = intval($days) + 1;
$txid = "tx$day_number";
$end_time = $end_date->format('Y-n-j')
$end_time .= TIME_SUFFIX
?>
This example assumes that you start counting days from 2014-3-26 (day 1) and the endtime is always 2 days later at 20:30:00. You can alter the constants to get a different behavior.
Am trying to get the time difference between two days. But for certain date/time, I get wrong answers
Here is my code:
/****************************************
$start_date = new DateTime('23:58:40'); *These two still give
$end_date = new DateTime('00:00:00'); *a wrong answer
*****************************************/
$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');
$dd = date_diff($end_date, $start_date);
//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
The awnser is correct. You provide two times. Without a date there is no way to know the last date is actually the next day. Just because you named the variable "end_date" doesnt mean PHP knows what you mean.
Perhaps you should include the date aswell in your request like
$start_date = new DateTime('2012-12-07 23:58:40');
$end_date = new DateTime('2012-12-08 00:11:36');
If you realy want to work with just times:
function differenceInTimes($start, $end) {
if (strtotime($start)>strtotime($end)) {
//start date is later then end date
//end date is next day
$s = new DateTime('2000-01-01 '.$start);
$e = new DateTime('2000-01-02 '.$end);
} else {
//start date is earlier then end date
//same day
$s = new DateTime('2000-01-01 '.$start);
$e = new DateTime('2000-01-01 '.$end);
}
return date_diff($s, $e);
}
$start_date = '23:58:40';
$end_date = '00:11:36';
$dd = differenceInTimes($start_date, $end_date);
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
//Hours = 0, Minutes = 12, Seconds = 56
Swap the arguments to date_diff
$dd = date_diff($start_date, $end_date);
Edit
After actually testing this theory it proved to be totally useless, giving the same answer.