In an online course I operate I am trying to track a user's totalTime spent taking the course over multiple user sessions.
I can calculate the totalTime a user has spent during first session by subtracting timeStarted from timeEnded using PHP. I am able to get a totalTime in hh:mm:ss.
This time I can store in MySQL.
My problem arises when i try to add the time from first session (hh:mm:ss) to a total time from a second session (hh:mm:ss) using PHP. The answer will allow me to track cumulative time spent over multiple sessions.
Any suggestions of how to add time(hh:mm:ss) to time(hh:mm:ss) in PHP?
Any input is greatly appreciated.
Sean
Add time(hh:mm:ss) to time(hh:mm:ss)
Moderator: General Moderators
Re: Add time(hh:mm:ss) to time(hh:mm:ss)
It'd be a lot easier if you tracked the time spent on the course in seconds. Then when you want to display it you do a bit of math.
- flying_circus
- Forum Regular
- Posts: 732
- Joined: Wed Mar 05, 2008 10:23 pm
- Location: Sunriver, OR
Re: Add time(hh:mm:ss) to time(hh:mm:ss)
Sean,tapaway wrote:Any suggestions of how to add time(hh:mm:ss) to time(hh:mm:ss) in PHP?
Basically what Tasairis said is the easist way. Store your time in a timestamp. A timestamp is defined as the number of seconds elapsed since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds.
strtotime() takes a string and converts it to a timestamp. It understands ALOT of variations of time formats.
Code: Select all
<?php
$accrued_time = strtotime("10:38:46");
$current_session = strtotime("2:28:39") - strtotime("00:00:00");
print date("H:i:s", ($accrued_time + $current_session));
// Prints: 13:07:25
?>I played with it a bit and came up for a text based solution, but I think its terrible and prone to errors.
Code: Select all
<?php
$accrued_time = explode(":", "10:38:46");
$current_session = explode(":", "2:28:39");
// Total Time: 13:07:25
if(count($accrued_time) == count($current_session)) {
# Define Variable for New Time
$new_time = array();
# Add it up!
for($i=0; $i<count($accrued_time); $i++) {
$new_time[$i] = $accrued_time[$i] + $current_session[$i];
}
# Carry time if minutes or seconds are greater than 59
for($i=(count($new_time) - 1); $i>=0; $i--) {
if($new_time[$i] >= 60) {
$new_time[$i - 1] += intval($new_time[$i] / 60);
$new_time[$i] = $new_time[$i] % 60;
}
}
# Display Results
printf("%d:%02d:%02d", $new_time[0], $new_time[1], $new_time[2]);
// Prints: 13:07:25
}
?>Re: Add time(hh:mm:ss) to time(hh:mm:ss)
Thank you both. I will give it a go.
There are many scripts to calculate a difference between 2 times but not to sum them.
Thanks again.
Sean
There are many scripts to calculate a difference between 2 times but not to sum them.
Thanks again.
Sean