PHP count up timer from variable - php

I have a page that shows the status of a TeamSpeak server on which I user ServerQuery to get the server's uptime using $uptime. This displays the server uptime as a total in seconds and I convert it to days, hours, minutes and seconds using
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
I output the uptime in the above format using secondsToTime($uptime); but I would like for the output to count up from the original output once the page is loaded instead of having to refresh the page to get the new uptime.
Thanks in advance.

You should use JavaScript to make a simple timer.
var timeelm, time, days, hours, minutes, seconds;
timeelm = document.getElementById("time");
time = timeelm.innerHTML;
days = parseInt(time.split(" ")[0]);
hours = parseInt(time.split(" ")[2]);
minutes = parseInt(time.split(" ")[4]);
seconds = parseInt(time.split(" ")[7]);
timerGo();
function timerGo() {
seconds++;
if (seconds == 60) {
minutes++;
seconds = 0;
}
if (minutes == 60) {
hours++;
minutes = 0;
}
if (hours == 24) {
days++;
hours = 0;
}
timeelm.innerHTML = days+" days, "+hours+" hours, "+minutes+" minutes and "+seconds+" seconds";
setTimeout(timerGo, 1000);
}
Note: Make sure that your webpage has an element assigned an ID of time.
Check out this fiddle.

Related

Time() By 5 Minutes Select

PHP Function to convert time() seconds to time format Hour:Minutes
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
return $dtF->diff($dtT)->format('%h:%i');
}
echo secondsToTime(time());
I need a function for something like:
If time now is 23:41 (hour:minute) to show 23:40
If time now is 23:46 (hour:minute) to show 23:45
If time now is 23:47 (hour:minute) to show 23:45
If time now is 23:49 (hour:minute) to show 23:45
If time now is 23:52 (hour:minute) to show 23:50
But the output to be show by time() format seconds so this way i can check via mysql how many rows updated from time() format show 23:45 if time now is 23:49 so in past 4 minutes ...
You need to round the minutes and then reformat your output date.
There's some gotchas hidden in here. As you can end up with 60 minutes (should be 00) and 24 hours (also should be 00). So special checks are put in place to catch that.
Also, you way of getting the current time is very convoluted. Getting "now" gets the same value which is what DateTime() gets by default.
function secondsToTime() {
$now = new \DateTime();
$cminutes = $now->format('i');
$hour = $now->format('H');
$nminutes = (round($cminutes)% 5 === 0) ? round($cminutes) : round(($cminutes + 5 / 2) / 5 ) * 5;
if ($nminutes > $cminutes) {
$nminutes -= 5;
}
if ($nminutes === 60) {
$nminutes = 0;
$hour++;
}
if ($hour === 24) {
$hour = 0;
}
return sprintf('%02d:%02d', $hour, $nminutes);
}
echo secondsToTime();
Demo

How to subtract a DateTime by a changing time

I've seen various posts asking how to subtract a specific number of hours, days, etc from a DateTime - but my question is a bit different.
Say I have a user log in, and the system records the date/time. Every second, a timer increases based on the difference between the current date/time and the recorded date/time - effectively creating a log-in timer. Then, the user decides to pause the timer, so the system records pause start and pause end (for when they resume). What I would like to do is make the displayed time subtracted by the pause time - such that the timer doesn't 'increase' while paused. Because I'm not using an actual counter adding up every second, in which case I could just not count up during lunch, I am unaware how to calculate the proper value on the timer.
Here is the code on displaying the timer (part of incriment.php):
date_default_timezone_set('America/Chicago');
$date = new DateTime(date('m/d/Y H:i'));
$date2 = new DateTime(date($_SESSION['date_in'] . ' ' .
$_SESSION['time_in']));
$interval = $date->diff($date2);
$interval = $interval->format('%H:%I');
$_SESSION['current_timer'] = $interval;
echo $_SESSION['current_timer'];
And here is the code on being paused
if(isset($_SESSION['paused']) && $_SESSION['paused'] === true) {
echo '<div class="info">';
echo '<img src="images/information-button" style="max-width:3em">';
if(isset($_SESSION['pause_start'])) {
date_default_timezone_set('America/Chicago');
if(isset($_SESSION['pause_end'])) {
$time = $_SESSION['pause_end']->diff($_SESSION['pause_start']);
echo '<br>Current pause time: ' . $time->format('%H:%I');
} else {
$time = new DateTime(date('H:i'));
$time = $time->diff(new DateTime($_SESSION['date_pause_start'] . ' ' . $_SESSION['pause_start']));
$_SESSION['pause_timer'] = $time->format('%h hours, %i minutes');
echo '<br>Pause timer: ' . $time->format('%h hours, %i minutes');
}
echo '</div>';
}
}
TLDR; How can I subtract a DateTime by an object returned by diff when I don't know if that diff will return minutes (say 30 minutes) or hours (say 1 hour, 30 minutes). I can't do this as a result of not knowing that, nor can I do something like $date->modify("+30 minutes") because I don't know if it's minutes or hours or what. I feel like it should be easy because in my lunch calculations, $time is displaying the time paused (ex: 30 minutes) and by using that into a string I could use the$date->modify strategy - but that's not working (See below what I tried in my incriment.php I showed earlier)
$interval = $interval->format('H:i');
if(isset($_SESSION['pause_timer'])) {
$interval = new DateTime(date($interval));
$interval = $interval->modify("-". $_SESSION['pause_timer']);
echo '-' . $_SESSION['pause_timer'];
}
But that echo's out -0 hours, 40 minutes if the user was paused for 40 minutes - and changes the time from 01:48 to 14:18 which is really confusing as it should be 1:08 obviously. That means to me that I'm improperly using the DateTime for my situation, is there a better solution
Thank you!
Edit: The user can only pause once per session for simplicities sake
I appreciate the replies in comments [even those they deleted ;) ], I managed to get it working by changing the paused code at the $_SESSION['pause_timer'] = $time->format('%h hours, %i minutes') into $_SESSION['pause_timer'] = $time->format('-%h hours, -%i minutes'). My problem was that I was subtracting only the hours, so when my time was only in minutes it added the minutes and subtracted the 0 hours!

How to convert working hours to working days?

I want to display a number of hours in days and hours as a human readable string but I need that 1 day be equal to 7 hours, so a working day.
I found this solution, but based on 1 day equal to 24 hours :
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}
source: Convert seconds into days, hours, minutes and seconds
DateTime won't help here. You need to count it on your own.
But this is simple math. Integer division for days and modulo for hours.
$hours = 12345;
$days = floor($hours/7);
$restHours = $hours%7;
echo "{$days} days, {$restHours} hours"; //1763 days, 4 hours
Custom made code to deal with this (probably on of 1000 ways on can implement this, I don't claim this to be the best, or good or anything like that).
function secondsToTime($seconds) {
$totalMinutes = intval($seconds / 60);
$totalHours = intval($totalMinutes / 60);
$totalDays = intval($totalHours / 7);
echo "$totalDays days and ".($totalHours%7)." hours ".($totalMinutes%60)." minutes and ".($seconds%60)." seconds";
}
e.g.
secondsToTime(8*60*60);
prints
1 days and 1 hours 0 minutes and 0 seconds

How to embed numbers values in a Date function in php then get difference?

I have a file in which i have to calculate the total hours of the time spent.
But the problem is that the data i am receiving is broken into Hours and Minutes.
I am converting it to the date() function and then find the difference with PHP built-in time_diff() function. But not succeeded yet..
Kindly help....
Here is my Data i am Fetching:
$HoursIn = $ls[$j][2]; // Punch-In Hours (e.g: 09)
$MinutesIn = $ls[$j][3]; // Punch-In Minutes (e.g: 38)
$TimeIn = $HoursIn.":".$MinutesIn; // Punch-In Total Time (e.g: 09:38)
$HoursOut = $ls[$j][4]; // Punch Out Hours (e.g: 17)
$MinutesOut = $ls[$j][5]; // Punch Out Minutes (e.g: 44)
$TimeOut = $HoursOut.":".$MinutesOut; // Punch-Out Total Time (e.g: 17:44)
I have tried this:
$HoursIn = 09; // Punch-In Hours (e.g: 09)
$HoursIn->format('%h');
$MinutesIn = 38; // Punch-In Minutes (e.g: 38)
$MinutesIn->format('%i');
$TimeIn = $HoursIn.":".$MinutesIn; // Punch-In Total Time (e.g: 09:38)
$HoursOut = 17; // Punch Out Hours (e.g: 17)
$HoursOut->format('%h');
$MinutesOut = 44; // Punch Out Minutes (e.g: 44)
$MinutesOut->format('%i');
$TimeOut = $HoursOut.":".$MinutesOut;
echo $interval = $TimeOut->diff($TimeIn);
But getting fatal Error...
Here you are my solution. The result for a sample is 1 hour and 3 mins. Hope it is clear but if any questions - ask me:
<?php
$in_time=sprintf("%04u-%02u-%02u %02u:%02u:02u",2015,5,6,12,5,0); // Values : Year Month Day hour min sec
$out_time=sprintf("%04u-%02u-%02u %02u:%02u:02u",2015,5,6,17,8,0); // Values : Year Month Day hour min sec
$TimeIn = new DateTime($in_time);
$TimeOut = new DateTime($out_time);
$interval = $TimeIn->diff($TimeOut);
echo $interval->format('%h:%i');
?>
#MarkBaker I have done this with your help! Thanks!
I got the result like this:
$HoursIn = $ls[$j][2]; // Punch-In Hours
$MinutesIn = $ls[$j][3]; // Punch-In Minutes
$timein = gmdate('H:i:s', $HoursIn*60*60+$MinutesIn*60);
$HoursOut = $ls[$j][4]; // PunchOut Hours
$MinutesOut = $ls[$j][5]; // PunchOut Minutes
$timeout = gmdate('H:i:s', $HoursOut*60*60+$MinutesOut*60);
$time1 = new DateTime($timein);
$time2 = new DateTime($timeout);
$interval = $time1->diff($time2);
$interval->format('%H:%i');
But Now I want to put a condition but the condition is not working: (I want to make $interval= 00:00 but this if condition is not working...)
if($timeout == "00:00:00") {$interval->format('%0:%0');}

How to find at what time activity finished?

I have activity start time and and total hour i just want to find the end time of that activity i mean time when activity finished ?
for example I start my activity
for
$hour = 24:60:08 // 24 hour 60 min 8 min total hour
$starttime = 13:09 // using 24 hour format it 01:09
//means activity start at = 13:09
$endtime = ?
I want to find out the the time finished time of an activity
Thanks
You can with adding to time exploded hour like following:
$hour = '24:60:08';
$starttime = '13:09';
$times = explode(':', $hour);
$timestamp = strtotime($starttime) + ($times[0] * 3600 + $times[1] * 60 + $times[2]);
$endtime = date('H:i', $timestamp);
echo $endtime; // 14:09
Explain:
24 = 24(hours) * 60(mins) * 60(secs)
60 = 60(mins) * 60(secs)
08 = 8(sec)
It appears like you have a start time of an activity and then a duration of how long it ran and you want to compute what's the end time. Your question becomes unclear by your use of non descriptive variable names nor any comments. You can do
<?php
$duration = "25:00:08";
$starttime = "13:09";
list($hours,$minutes,$seconds) = explode(":",$duration);
$totalTime = $seconds+($minutes*60)+($hours*3600);
$endTime = date("h:i",strtotime($starttime)+$totalTime);
echo $endTime;
?>
Sidenote: 24:60:08, 60 minutes is nothing. That's 25 hours 0 minutes and 8 seconds
If you want to get the time elapsed to process something, let's say to execute a function, you can easily do it with PHP microtime.
Assume you want to find time elapsed to execute function test, here how you do this.
public function test()
{
$time_start = microtime(true);
/*
Your code
goes here
*/
$time_end = microtime(true);
$execution_time = (($time_end - $time_start) / 60) * 60;
echo $execution_time; //This will show you the execution time in seconds.
}
If you want, you can add this seconds to any previous time stamp you saved, in order to get the execution terminated time in hh:mm:ss format. Hope this helps.
Cheers!
I am unable to understand exactly what you are looking for
<?php
$hour = "24:60:08"; // 24 hour 60 min 8 min total hour
$starttime = "13:09";
$hourArray=explode(":", $hour);
$starttimeArray=explode(":", $starttime);
$endtimearray=array();
for ($i=0;$i<3;$i++){
//Verifyng time is set else making it zero
if (!isset($hourArray[$i]))
$hourArray[$i]=0;
if (!isset($starttimeArray[$i]))
$starttimeArray[$i]=0;
$endtimearray[$i]=$hourArray[$i]-$starttimeArray[$i];
}
echo $endtimearray[0];
for ($i=1;$i<3;$i++)
echo ":$endtimearray[$i]";
Hopefully This is what you are looking for.

Categories