I have a big problem for getting/computing the minutes.
Scenario:
I have a form which is the user can input the seconds [5s, 10s, 25s, 30s, 60s]. I called the table "Duration"
I already have "Duration" [compose of minutes:seconds], in my database which is "1:5" [the last input]. Then I insert again another seconds "10s"...
*the format is minutes:seconds
The correct output should be: 1:15
The current result is : 0:15
AS we see. I have a problem in computing the minutes. The codes I will show is good for subtracting the seconds. But now I need to revised it to adding the seconds.
Here's my code:
$duration = $_POST["duration"];
if(sizeof($bldg) == 1)
{
$total = sizeof($bldg)-1;
}
else
{
$total = sizeof($bldg)%2;
}
for($i=0; $i<sizeof($bldg);$i++)
{
$result = mysql_query("SELECT fldTotalDuration FROM tbldata WHERE fldNetname = '".$network."' AND fldBldgName = '".$bldg[$i]."' AND fldWeek = '".$week."' AND fldMonth = '".$month."' ");
if(mysql_num_rows($result)==0)
{
$totalduration = "";
$seconds = 0;
$minutes = 0;
$computeSecMin = $seconds * $minutes;
$subSecMin = $computeSecMin + $duration;
$getMin = floor($subSecMin/60);
$getSec = $subSecMin%60;
$totalduration = $getMin .":". $getSec;
}
else{
$row = mysql_fetch_array($result);
$time = explode(":",$row['fldTotalDuration']);
$dur = explode(" ",$duration);
$computeSecMin = 60 * $time[0];
$subSecMin = $computeSecMin + $time[1] + $dur[0];
$getMin = floor($subSecMin/60);
$getSec = $subSecMin%60;
$totalduration = $getMin .":". $getSec;
}
}
$query = "INSERT INTO tbldata(fldNetname,fldBldgName,fldPlaylist,fldMonth,fldWeek,fldDuration,fldFrom,fldTo,fldTotalDuration) VALUES ('".$network."','".$bldg[$i]."','".$AdName."','".$month."','".$week."','".$duration."','".$from."','".$to."', '".$totalduration."')";
mysql_query($query) or die (mysql_error());
$duration = is came from another form where its a combobox/dropdown that is consists of 5s, 10s, 25s, 30s, 60s.
Currently, for adding the seconds is okay but for minutes is not good.
my problem for the computation is this "$getMin = floor($subSecMin/60); " .The result of this is "0" but it should be "1" because this computation is for "minutes".
Thanks for helping me with this problem.
Actually, what you got is what you should get.
If
$time = [0, 5]
and
$dur = [10, s]
then
$computeSecMin = 60 * $time[0] = 60*0 = 0
and
$subSecMin = $computeSecMin + $time[1] + $dur[0] = 0 + 5 + 10 = 15
Thus
$getMin = floor($subSecMin/60) = floor(15/60) = floor(0.25) = 0
It seems to me that you are computing it right, and the result is indeed 0 minutes.
The problem is your duration variable. It seems to me that your program is getting the wrong value. If I understand, it should be [1, 5] and not [0,5]. Check the function that is getting this value.
Here is what you are trying to do (sorry, I changed variables names, yours were not obvious):
$time = array(1,5);
$time_plus = '10s';
$time_plus = preg_replace('#\D#', '', $time_plus);
$minutes = $time [0] + (($time_plus + $time[1] >= 60) ? 1 : 0);
$seconds = ($time[1] + $time_plus) % 60;
echo $new_time = $minutes . ":" . $seconds;
Demo: http://codepad.org/eOBNeHrq
You may find using mysql for time manipulations will be cleaner for your application. AddTime() lets you do what you want with only seconds and minutes.
SELECT ADDTIME('00:32.50','1:27.50');
gives the result of:
01:59:01.000000
So, this adds 32.5 seconds to 1 minute 27.50 seconds = 1 minutes 59 seconds and .01 milliseconds.
Related
i have two different break time
default break time
extra break time
here i want to sum of two times and display 12 hrs format
EX :
$default_time = "00:30";
$extra_time = "00:25";
my expected output : 00:55
but now display 01:00
this is my code
$default_time = $work_data->break_time;
$break_time = $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
Here is the function you can calculate total time by passing the arguments to functions.
$hours, $min are supposed variable which is zero
$default_time = "00:30";
$break_time = "00:25";
function calculate_total_time() {
$i = 0;
foreach(func_get_args() as $time) {
sscanf($time, '%d:%d', $hour, $min);
$i += $hour * 60 + $min;
}
if( $h = floor($i / 60) ) {
$i %= 60;
}
return sprintf('%02d:%02d', $h, $i);
}
// use example
echo calculate_total_time($default_time, $break_time); # 00:55
There is one function call to strtotime function too much.
You should leave out the strtotime() call in the last line, as $total_break already is a UNIX timestamp:
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",$total_break);
The problem is that you're trying to add too specific timestamps, but what you're trying to achieve is adding two durations. So you need to convert those timestamps into durations. For that you need a base, which in your case is 00:00.
$base = strtotime("00:00");
$default_time = $work_data->break_time;
$default_timestamp = strtotime($default_time);
$default_duration = $default_timestamp - $base; // Duration in seconds
$break_time = $work_data->extra_time;
$break_timestamp = strtotime($break_time);
$break_duration = $break_timestamp - $base; // Duration in seconds
$total_break = $default_duration + $break_duration; // 55 min in seconds
// If you want to calculate the timestamp 00:55, just add the base back to it
echo date("H:i", $base + $total_break);
Consider using standard DateTime and DateInterval classes. All you will need is to convert your second variable value to interval_spec format (see http://php.net/manual/en/dateinterval.construct.php for details):
$defaultTime = "00:30";
$breakTime = "PT00H25M"; // Or just 'PT25M'
$totalBreak = (new DateTime($defaultTime))->add($breakTime);
echo $totalBreak->format('H:i');
You could try the following code fragment:
$time1 = explode(":", $default_time);
$time2 = explode(":", $break_time);
$fulltime = ($time1[0] + $time2[0]) * 60 + $time1[1] + $time2[1];
echo (int)($fulltime / 60) . ":" . ($fulltime % 60);
<?php
$time = "00:30";
$time2 = "00:25";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
print_r($result);
?>
Use below code you will definitely get your answers.
$default_time = "00:30:00";
$extra_time = "00:25:00";
$secs = strtotime($extra_time)-strtotime("00:00:00");
$result = date("H:i:s A",strtotime($default_time)+$secs);
echo $result;die;
You can modify above code as per your need.
You could try the following:
$default_time = $work_data->break_time;
$date_start = new DateTime($default_time);
$break_time = $work_data->extra_time;
$interval = new DateInterval("PT" . str_replace(":", "H", $break_time) . "M");
$date_end = $date_start->add($interval);
echo $date_end->format("H:i");
Note that this doesn't account for times which span a 24 hour period
i have lets say a $value = 5; and the valnue means 5 minutes, and i have a file saved on the server and getting modified a lot called check.txt i want a code to do a calculation of if timenow - timemodification of file <= 0 in H:i:s from the main $value of 5 minutes then continue, else echo please wait minutes left from the time now - filetimemodification of the main value of 5 minutes = $timeleft in m:s format.
i'm testing on the current code but i keep getting a value of -1376352747
my code which is know is bad :) is
$filename = 'check.txt';
$time = date("H:i:s");
$time = str_replace("00", "24", $time);
$filemodtime = filemtime($filename);
$timeleft = $time - $filemodtime;
$h = explode(':', $time);
$h = $h[0];
$h = str_replace("00", "24", $h);
$m = explode(':', $time);
$m = $m[1];
$s = explode(':', $time);
$s = $s[2];
$hms = ("$h:$m:$s");
if (count($filemodtime - $time) <= 0) {
echo "you can continue";
}
else {
echo " please wait $timeleft";
}
thanks in advance
The filemtime() function returns a UNIX-timestamp in seconds, and the time() function returns the current time as a UNIX-timestamp. So by using that difference, you get the file's age in seconds.
$age = time() - filemtime($filename);
// if older then 5 minutes (5 * 60 secounds)
if($age > $value*60)
{
// good
}
else
{
$time_left = $value * 60 - $age;
$time_left_secounds = $time_left % 60;
$time_left_minutes = ($time_left - $time_left_secounds) / 60;
$formated_time_left = sprintf("%02d:%02d", $time_left_minutes, $time_left_secounds);
echo "Please wait {$formated_time_left}";
}
I would recommend to work with time() rather than date().
that way, you can substract the file time from the current time() function, and see if it is bigger than 5 minutes * 60 seconds.
Good luck!
How to increase seconds in a variable ?
to increase in a date .. :
date("m/d/Y h:i:s a", time() + 30);
but i want to do this :
$seconds = 59;
$increase = 3;
$result = $seconds + $increase; // 62
i want it to stop by second 60 and re-calculate, the result should become 2 and not 60
You want the modulus operator:
$seconds = 59;
$increase = 3;
$result = ($seconds + $increase) % 60; // 2
I want to add up time in php but after hours of google'ing and trying out im still unable to find a solution.
my values are:
$newTotal = '00:45:00';
$oldTotal = '00:16:00';
I want to add those two up which make 01:01:00.
Can you give me an example i'm getting really desperate! :p
thanks in advance,
Use strtotime() to turn them into Unix timestamps, then add them as integers:
$newTotal = '00:45:00';
$oldTotal = '00:16:00';
$total = strtotime($newTotal) + strtotime($oldTotal);
To format it as hh:mm:ss again, use date():
echo date('H:i:s', $total);
This gives:
01:01:00
If these values always look like that, you could break them down with a substr()
$hours1 = substr($newTotal, 0, 2);
etc. And then simply add up the seconds, do a divide and mod and bubble up to the hours, and voila!
$secondstotal = $seconds1+$seconds2;
$restseconds = $secondstotal % 60;
$minutesfromseconds = floor($restseconds / 60);
$minutestotal = $minutes1+$minutes2+$minutesfromseconds;
etc.
keep a start date for minimum error.
<?php
$origin = '00:00:00';
$newTotal = '00:45:00';
$oldTotal = '00:16:00';
$added = strtotime($newTotal) + (strtotime($oldTotal) - strtotime($origin));
echo date('H:i:s', $added );
output :
01:01:00
Note, if your time is more than 23:59:59 after adding, you will get wrong result.
Another solution without time function:
function sumtotal($a,$b) {
$i = explode(':',$a);
$j = explode(':',$b); // 0hh:1mm:2ss
$k = array(0,0,0,0); // 0days:1hours:2minutes:3seconds
$k[3] = $i[2]+$j[2];
$k[2] = (int)($k[3]/60)+$i[1]+$j[1];
$k[1] = (int)($k[2]/60)+$i[0]+$j[0];
$k[0] = (int)($k[1]/24);
$k[3] %= 60;
$k[2] %= 60;
$k[1] %= 24;
if ($k[3]<10) $k[3] = '0'.$k[3];
if ($k[2]<10) $k[2] = '0'.$k[2];
if ($k[1]<10) $k[1] = '0'.$k[1];
return $k[0].' days : '.$k[1].' hours : '.$k[2].' minutes : '.$k[3].' seconds';
}
$newTotal = '01:45:21';
$oldTotal = '03:16:56';
echo sumtotal($newTotal,$oldTotal); // result: 0 days : 05 hours : 02 minutes : 17 seconds
I can't wrap my brain around this one so I hope someone can help. I have a song track that has the song length in milliseconds. I also have the date the song played in DATETIME format. What I am trying to do is find out how many milliseconds is left in the song play time.
Example
$tracktime = 219238;
$dateplayed = '2011-01-17 11:01:44';
$starttime = strtotime($dateplayed);
I am using the following to determine time left but it does not seem correct.
$curtime = time();
$timeleft = $starttime+round($tracktime/1000)-$curtime;
Any help would be greatly appreciated.
For my needs I used the following approach:
$curTime = microtime(true);
// something time consuming here
...
// get time difference in milliseconds
$timeConsumed = round(microtime(true) - $curTime,3)*1000;
So, the point is that we use float representation of time here (see http://php.net/manual/en/function.microtime.php)
Hope you will adopt it for your needs.
i use the following set of functions for handling mysql dates, maybe they can help you:
function sqlArray($date, $trim=true) {
$result = array();
$result['day'] = ($trim==true) ? ltrim(substr($date,8,2),'0') : substr($date,8,2);
$result['month'] = ($trim==true) ? ltrim(substr($date,5,2),'0') : substr($date,5,2);
$result['year'] = substr($date,0,4);
$result['hour'] = substr($date,11,2);
$result['minutes'] = substr($date,14,2);
return $result;
}
function sqlInt($date) {
$date = sqlArray($date);
return mktime($date['hour'], $date['minutes'], 0, $date['month'], $date['day'], $date['year']);
}
function difference($dateStart, $dateEnd) {
$start = sqlInt($dateStart);
$end = sqlInt($dateEnd);
$difference = $end - $start;
$result = array();
$result['ms'] = $difference;
$result['hours'] = $difference/3600;
$result['minutes'] = $difference/60;
$result['days'] = $difference/86400;
return $result;
}
in your case it should be something like:
$dateplayed = '2011-01-17 11:01:44';
print_r(difference($dateplayed, date('Y:m:d')));
hope it works :D
I have written this function to calculate duration between given two timestamps (with milliseconds).
function calculateTransactionDuration($startDate, $endDate)
{
$startDateFormat = new DateTime($startDate);
$EndDateFormat = new DateTime($endDate);
// the difference through one million to get micro seconds
$uDiff = ($startDateFormat->format('u') - $EndDateFormat->format('u')) / (1000 * 1000);
$diff = $startDateFormat->diff($EndDateFormat);
$s = (int) $diff->format('%s') - $uDiff;
$i = (int) ($diff->format('%i')) * 60; // convert minutes into seconds
$h = (int) ($diff->format('%h')) * 60 * 60; // convert hours into seconds
return sprintf('%.6f', abs($h + $i + $s)); // return total duration in seconds
}
$startDate = '02-Mar-16 07.22.13.000548';
$endDate = '02-Mar-16 07.22.14.000072';
$difference = calculateTransactionDuration($startDate, $endDate);
//Outputs 0.999524 seconds
You could convert the datetime string/input into unixtimestamp and then get the difference. If you do have milliseconds, unixtimestamp would have digits after the decimal. Once you have the difference, you can convert that value back into your date time pattern using function date in php. Below is the link.
Good luck!
http://php.net/manual/en/function.date.php
I used this function for my self:
public function calculateStringTimeToMiliseconds($timeInString)
{
$startTime = new \DateTime("now");
$endDate = new \DateTime($timeInString);
$interval = $startTime->diff($endDate);
$totalMiliseconds = 0;
$totalMiliseconds += $interval->m * 2630000000;
$totalMiliseconds += $interval->d * 86400000;
$totalMiliseconds += $interval->h * 3600000;
$totalMiliseconds += $interval->i * 60000;
$totalMiliseconds += $interval->s * 1000;
return $totalMiliseconds;
}