How to get time difference in milliseconds - php

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;
}

Related

How to convert h:m:s to float and float to h:m:s php

I want to convert time value with second to float and than do some calculation on it and convert it again to time value using php
I have used the function describe below but it has only hour and minute calculation it display wrong amount if second value is there.
i found this function from time conversion to float
I have used function for convert time to float is
function hours_tofloat($val){
if (empty($val)) {
return 0;
}
$parts = explode(':', $val);
return $parts[0] + floor(($parts[1]/60)*100) / 100;
}
hours_tofloat("00:02:37");
if i use above function for 00:02:37 time value it gives me wrong float no 0.03 because above function dose not have option for second. so help me and guide how to calculate it
Modify your code as follows. It will return the time in seconds.
$val = '00:02:37';
function hours_tofloat($val){
if (empty($val)) {
return 0;
}
$parts = explode(':', $val);
return (int) (($parts[0] * 60 *60) + $parts[1]*60 + $parts[2]);
}
echo hours_tofloat($val);
Output: 00:02:37 = 157
It returns
157
Why don't you use EPOCH time routines? Epoch time is an integer representing seconds based on 1 Jan 1970. You don't need the date part so you can have the following approach:
<?php
$time = '00:02:37';
$date = new DateTime("1970-01-01T$time+00:00");
echo 'Seconds = '.$date->format('U');
?>
Output
Seconds = 157
$val = "00:02:37";
/* function converts time value to float */
function time_to_float($val){
$parts = explode(':', $val);
$hour_val = 0;
$hour_val = $parts[0];
$min_val = $parts[1];
$second_val = $parts[2];
return ($hour_val +(($min_val* 1/60))+($second_val * 1/3600));
}
$value = time_to_float($val);// 0.043611111111111
/* function to convert float to time */
$res = float_to_time($value);//00:02:37
function float_to_time($value){
$value1 = explode('.',$value);
$hours = $value1[0];
$min_in_float = ($value - $hours) * 60/1;
$min_val = explode('.',$min_in_float);
$min_val = $min_val[0];
$min_in_float = $min_in_float - $min_val;
$second_val = $min_in_float * 60/1;
$second_val = round($second_val);
if($hours < 10){
$hours = "0".$hours;
}
if($min_val < 10){
$min_val = "0".$min_val;
}
if($second_val < 10){
$second_val = "0".$second_val;
}
return $hours.":".$min_val.":".$second_val;
}
I got reference about the calculation from
https://www.calculatorsoup.com/calculators/time/time-to-decimal-calculator.php
https://www.calculatorsoup.com/calculators/time/decimal-to-time-calculator.php
With strtotime I get the seconds immediately. UTC must be used as the time zone.
$time = '00:02:37';
$seconds = strtotime('1970-01-01 '.$time.' UTC'); //157
gmdate can be used to convert an integer into a time H:i:s.
$seconds = 157;
$timeHis = gmdate('H:i:s',strtotime('1970-01-01 UTC +'.$seconds.' Seconds'));
//'00:02:37'
The number of hours must not exceed 23 and the number of seconds $seconds must be less than 86400 (= 1 Day). Negative times are also not supported.

PHP sum two different minutes

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

php where is my percentage of the day being calculated wrong?

I been trying to fix this php percentage calculator of the day...basically right now here is about 230pm and I am getting 73% of the day completed....it should be more like 60% of the day. Here is the code:
$now = time();
$today = strtotime(date("m/d/Y"));
$seconds = $now - $today;
$day = 24*60*60;
$percent = $seconds / $day*100;
I attempted to write my own version but I am getting 100% of the day...Here is the code:
$todaysTime = time();
$todaysStart = time()-86400;
$todayCalc = $todaysTime - $todaysStart;
$dayPhpOne = 24*60*60;
$percentDay = $todayCalc / $dayPhpOne*100;
It is done in php where am I messing up my code?
Try this:
$percentDay = time() % 86400 / 864;
Edit
From the comments I take, that I didn't elaborate on time zones. Let me make clear, that this is meant to be UTC day percent.
This solution does respect timezone and other time-related complexities:
$d = new DateTime();
$h = $d->format('H');
$m = $d->format('i');
$s = $d->format('s');
$currentSecond = $h * 3600 + $m * 60 + $s;
$midnight = new DateTime($d->format('Y-m-d'), $d->getTimezone());
$tomorrow = clone $midnight;
$tomorrow = $tomorrow->add(new DateInterval('P1D'));
$secondsToday = $tomorrow->getTimestamp() - $midnight->getTimestamp();
$percent = $currentSecond / $secondsToday * 100;
var_dump($percent);
If necessary - it's possible to specify a particular timezone to be used as a second DateTime constructor argument.

Adding up time in php

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

php replacing old code with DateTime class

I have a function that creates time intervals between two time marks. The function works but I'm struggling to upgrade from strtotime() and use the DateTime class.
Below is a patch of code I wrote without getting errors
$timestart = new DateTime("14:00:00");
$timestop = new DateTime("20:00:00");
$date_diff = $timestop->diff($timestart);
$time_diff = $date_diff->format('%H');
Next is the entire code untouched. I get DateInterval could not be converted to int erros using the code above. Please kindly advise how to correctly implement the class.
Live example: http://codepad.org/jSFUxAnp
function timemarks()
{
//times are actually retrieved from db
$timestart = strtotime("14:00:00");
$timestop = strtotime("20:00:00");
$time_diff = $timestop - $timestart; //time difference
//if time difference equals negative value, it means that $timestop ends second day
if ($time_diff <= 0)
{
$timestop = strtotime( '+1 day' , strtotime( $row->timestop ) ); //add 1 day and change the timetsamp
$time_diff = $timestop - $timestart;
}
//create interval
$split = 3;
$interval = $time_diff/$split;
//get all timemarks
$half_interval = $interval / 2;
$mid = $timestart + $half_interval;
for ( $i = 1; $i < $split; $i ++) {
//round intervals
$round_mid = round($mid / (15 * 60)) * (15 * 60);
$result .= date('H:i:s', $round_mid) . ", ";
$mid += $interval;
}
$round_mid = round($mid / (15 * 60)) * (15 * 60);
$result .= date('H:i:s', $round_mid);
return $result;
}
outputs 15:00:00, 17:00:00, 19:00:00
Actually you're using DateTime, these are just aliases for creating DateTime instances
The equivalent would look like this:
$timestart = new DateTime("14:00:00");
$timestop = new DateTime("20:00:00");
$date_diff = $timestop->diff($timestart);
$time_diff = $date_diff->format('%H');
So this has to work, I tested it and I got correct results!

Categories