Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have this data:
$t1 = '75:00'; //Corresponds to Hours:Minutes
$t2 = '05:13';
// I need to know the time diference in this example must return:
'69:47'
75:00 is not a valid time, but if you found yourself in a situation that you have to use that, use this code below
<?php
function convertToMinutes($time)
{
list($hour, $minutes) = explode(":", $time);
$hoursToMinutes = $hour * 60;
$addMinutes = $hoursToMinutes + $minutes;
return $addMinutes;
}
function convertToHours($time)
{
$hours = floor($time / 60);
$minutes = $time % 60;
if ($time < 60) {
return $time;
}
return $hours . ":" . $minutes;
}
function timeDifference($time1, $time2)
{
if ($time1 >= $time2) {
$diff = convertToMinutes($time1) - convertToMinutes($time2);
return convertToHours($diff);
}
$diff = convertToMinutes($time2) - convertToMinutes($time1);
return convertToHours($diff);
}
$t1 = '75:00';
$t2 = '05:13';
$answer = timeDifference($t1, $t2);
echo $answer;
You can use the below code to calculate time difference -
$t1 = new DateTime('23:00');
$t2 = new DateTime('05:13');
$interval = $t1->diff($t2);
echo $interval->format("%H:%i");
*75:00 is not a valid time. You have to take care of that.
Related
This question already has answers here:
Adding 30 minutes to time formatted as H:i in PHP
(7 answers)
Closed 8 years ago.
I want to add 2 time variable in php. I use below code but it returns a big number. how can I have a time like (15:20:00) at the end?
code :
$time1="10:00:00";
$time2="05:20:00";
$sum = strtotime($time1)+strtotime($time2);
echo date("H:i:s",$sum);
Expected result: 15:20:00
Add to the end
$sum = strftime('%H:%M:%S', $sum);
http://php.net/manual/en/function.strftime.php
Try something like :
echo sum_the_time($time1, $time2);
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
return "{$hours}:{$minutes}:{$seconds}";
}
I just edit my question
I have have two time format i want the difference between them
For example
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('100:30:00');
$interval = $time1->diff($time2);
echo $interval->format('%h:%i:%s second(s)');
?>
Its working fine below 24 hour showing me fatal error if i am increasing time2
$time2 = new DateTime('100:30:00');
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct() [datetime.--construct]: Failed to parse time string (100:30:00) at position 0 (1): Unexpected character' in D:\xampp\htdocs\datetime.php:3 Stack trace: #0 D:\xampp\htdocs\datetime.php(3): DateTime->__construct('100:30:00') #1 {main} thrown in D:\xampp\htdocs\datetime.php on line 3
Is there any other way or i can edit the same I have try a lot but not find out the soloution
I just want the diffrence using any method
Thanks
One way to do it:
$time2 = '100:00:00';
$time1 = '10:30:00';
list($hours, $minutes, $seconds) = explode(':', $time2);
$interval2 = $hours*3600 + $minutes*60 + $seconds;
list($hours, $minutes, $seconds) = explode(':', $time1);
$interval1 = $hours*3600 + $minutes*60 + $seconds;
$diff = $interval2 - $interval1;
echo floor($diff / 3600) . ':' .
str_pad(floor($diff / 60) % 60, 2, '0') . ':' .
str_pad($diff % 60, 2, '0');
Output:
89:30:00
Here is Codepad demo
I Hope this may help.
$time1 = '10:30:00';
$time2 = '100:00:00';
function hms2sec ($hms) {
list($h, $m, $s) = explode (":", $hms);
$seconds = 0;
$seconds += (intval($h) * 3600);
$seconds += (intval($m) * 60);
$seconds += (intval($s));
return $seconds;
}
$ts1=hms2sec($time2);
$ts2=hms2sec($time1);
$time_diff = $ts1-$ts2;
function seconds($seconds) {
// CONVERT TO HH:MM:SS
$hours = floor($seconds/3600);
$remainder_1 = ($seconds % 3600);
$minutes = floor($remainder_1 / 60);
$seconds = ($remainder_1 % 60);
// PREP THE VALUES
if(strlen($hours) == 1) {
$hours = "0".$hours;
}
if(strlen($minutes) == 1) {
$minutes = "0".$minutes;
}
if(strlen($seconds) == 1) {
$seconds = "0".$seconds;
}
return $hours.":".$minutes.":".$seconds;
}
echo $final_diff=seconds($time_diff);
Since I don't have enough "reputation" to add a comment to the selected answer. I want to add a message to point out to a flaw with it.
If you try it with these arguments:
$time2 = '10:15:00';
$time1 = '10:10:00';
You will get an incorrect result of:
0:50:00
To correct this, you need to add STR_PAD_LEFT within the str_pad that deals with the minute as in:
str_pad(floor($diff / 60) % 60, 2, '0', STR_PAD_LEFT) . ':' .
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: producing relative date/time from timestamps
please see the example of PHP code:
<?php
$now = date("Y-m-d H:i:s");
$comment_added = date("2012-05-25 22:10:00");
?>
As the output, I would like to get something like this (depending on when a comment has been added):
Comment has been added 21 minutes ago.
Comment has been added 15 hours ago.
Comment has been added 2 days ago.
Comment has been added 3 months ago.
Comment has been added 4 years ago.
I would like to get a function, where it will be selected automatically. Any examples would be appreciated.
This should work.
<?php
$now = date("Y-m-d H:i:s");
$comment_added = date("2012-05-25 22:10:00");
$diff = strtotime($now) - strtotime($comment_added);
if ($diff > (365*24*3600)) {
$type = 'year';
$value = floor($diff / (365*24*3600));
} else if ($diff > (30*24*3600)) {
$type = 'month';
$value = floor($diff / (30*24*3600));
} else if ($diff > (24*3600)) {
$type = 'day';
$value = floor($diff / (24*3600));
} else if ($diff > 3600) {
$type = 'hour';
$value = floor($diff / 3600);
} else if ($diff > 60) {
$type = 'min';
$value = floor($diff / 60);
} else {
$type = 'sec';
$value = $diff;
}
$plurial = '';
if ($value > 1)
{
$plurial .= 's';
}
echo "Comment added {$value} {$type}{$plurial} ago.";
?>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm working on something where I need to add a list of times togther in the following format mm:ss so 3:10 would be 3 minutes and 10 seconds.
So how for example would you go about the following sum in php?
2:10 + 3:15 + 6:59 + 2:22
Use following code :
$tarr = array('2:10', '3:15','6:59','2:22');
echo sum_the_time($tarr);
function sum_the_time($times) {
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
// $seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
Here is the demo : http://codepad.org/dJBY78wZ
Just for fun :)
function sumTime($times) {
$min = $sec = 0;
foreach($times as $time) {
list($cmin, $csec) = explode(':', $time);
$min += $cmin;
$sec += $csec;
}
return sprintf('%02d:%02d', $min + floor($sec/60), $sec % 60);
}
http://viper-7.com/txkHAs
<?php
function s($str) {
list($minutes,$seconds) = explode(':',$str);
return $minutes * 60 + $seconds;
}
function ms($seconds) {
return sprintf('%02d:%02d', $seconds/60, $seconds%60);
}
$seconds = s('2:10') + s('3:15') + s('6:59') + s('2:22');
echo ms($seconds);
http://codepad.viper-7.com/BUkRRM
You know when it's late in the night and your brain is fried? I'm having one of those nights right now, and my function so far is not working as it should, so please take a look at it:
(I should note that I'm using the PHP 5.2.9, and the function / method DateTime:Diff() is not available until PHP 5.3.0.
<?php
function time_diff($ts1, $ts2) {
# Find The Bigger Number
if ($ts1 == $ts2) {
return '0 Seconds';
} else if ($ts1 > $ts2) {
$large = $ts1;
$small = $ts2;
} else {
$small = $ts1;
$large = $ts2;
}
# Get the Diffrence
$diff = $large - $small;
# Setup The Scope of Time
$s = 1; $ss = 0;
$m = $s * 60; $ms = 0;
$h = $m * 60; $hs = 0;
$d = $h * 24; $ds = 0;
$n = $d * 31; $ns = 0;
$y = $n * 365; $ys = 0;
# Find the Scope
while (($diff - $y) > 0) { $ys++; $diff -= $y; }
while (($diff - $n) > 0) { $ms++; $diff -= $n; }
while (($diff - $d) > 0) { $ds++; $diff -= $d; }
while (($diff - $h) > 0) { $hs++; $diff -= $h; }
while (($diff - $m) > 0) { $ms++; $diff -= $m; }
while (($diff - $s) > 0) { $ss++; $diff -= $s; }
# Print the Results
return "$ys Years, $ns Months, $ds Days, $hs Hours, $ms Minutes & $ss Seconds.";
}
// Test the Function:
ediff(strtotime('December 16, 1988'), time());
# Output Should be:
# 20 Years, 11 Months, 8 Days, X Hours, Y Minutes & Z Seconds.
?>
This isn't an answer to your question, but I just wanted to point out...
while (($diff - $y) > 0) { $ys++; $diff -= $y; }
is a very inefficient way of writing
$ys = $diff / $y;
$diff = $diff % $y;
Also, this
else if ($ts1 > $ts2) {
$large = $ts1;
$small = $ts2;
} else {
$small = $ts1;
$large = $ts2;
}
# Get the Diffrence
$diff = $large - $small;
can easily be rewritten as
$diff = abs($ts1 - $ts2);
I have a feeling that the problem in your code would be more apparent if it was less verbose. :)
how about simplifying the first part with a simple
$diff = abs($ts2 - $ts1);
Then, when you do this:
$n = $d * 31; $ns = 0;
$y = $n * 365; $ys = 0;
you are actually saying that a year is composed of 365 31 day long months. which is actually about 36 year long years. Probably not what you want.
Finally, we are all grown ups here. Please use grown up variable names i.e. $YEAR_IN_SECONDS instead of $ys. As you can clearly see, you may write code once, but 20 other schmucks are going to have to read it a lot of times.
In the case of needed all months during the given times-stamp then we have use of the following coding in php :
function MonthsBetweenTimeStamp($t1, $t2) {
$monthsYear = array();
$lastYearMonth = strtotime(gmdate('F-Y', $t2));
$startYearMonth = strtotime(gmdate('F-Y', $t1));
while ($startYearMonth < $lastYearMonth) {
$monthsYear[] = gmdate("F-Y", $startYearMonth);
//Increment of one month directly
$startYearMonth = strtotime(gmdate("F-Y", $startYearMonth) . ' + 1 month');
}
if (empty($monthsYear)) {
$monthsYear = array($startYearMonth));
}
return $monthsYear;
How about this:
function time_diff($t1, $t2)
{
$totalSeconds = abs($t1-$t2);
$date = getdate($totalSeconds);
$firstYear = getdate(0);
$years = $date['year']-$firstYear['year'];
$months = $date['mon'];
$days = $date['mday'];
$hours = $date['hour'];
$minutes = $date['minutes'];
$seconds = $date['seconds'];
return "$years Years, $months Months, $days Days, $hours Hours, $minutes Minutes & $seconds Seconds.";
}
This uses the difference of the given times as a date. Then you can let the "getdate" do all the work for you. The only challenge is the number years - which is simply the getdate year (of the difference) minus the Unix epoch year (1970).
If you don't like using an actual month, you could also divide the "year" day by the number of days in 12 equal months
$months = $date['yday'] / (365/12);
Similarly days could be figured out the remaining days with modulus
$days = $date['yday'] % (365/12);