PHP Time difference only display when not zero - php

I'm calculating the difference between two dates (the current date and a date in the database). I want to display the difference in days and hours between the dates, but when the day-difference is 0 I don't want to display it. This is my code:
<?php
$to_time = new \DateTime($database_time);
$from_time = new \DateTime();
echo $from_time->diff($to_time)->format("%d %H");
?>
Output should be, for example:
> 50 days and 4 hours
> 1 day and 7 hours //and not 1 dayS
> 6 hours //and not 0 days and 6 hours
There are two issues with my own code: the first one is that it always display the number of days. The second one is that it is just a format. For example when the difference is 2 months, 6 days and 2 hours it displays: 6 days and 2 hours. But it should be 68 days and 2 hours (because of the two months).
Can't get it work with other codes I found. Thanks in advance!

Try this..
$seconds = strtotime("2012-10-10 02:40:03") - strtotime("2010-12-25 05:15:02");
echo $days = floor($seconds / 86400);
echo "</br>";
echo $hours = floor(($seconds - ($days * 86400)) / 3600);
echo "</br>";
echo $minutes = floor(($seconds - ($days * 86400) - ($hours * 3600))/60);
echo "</br>";
echo $seconds = floor(($seconds - ($days * 86400) - ($hours * 3600) - ($minutes*60)));

Related

PHP Date Calculator Returning Wrong Days

I'm using the below calculator to determine the years, months, and days between a set date and the current date. I thought it was working fine, but then it came up on the year mark and i noticed it was not working properly. Tomorrow is actually when the one year mark would be, but it is currently returning 11 months, 34 days. Could anyone tell me whats wrong? It should be 11 months, 30 days.
function relationshipTimer($functionDate)
{
$date1 = $functionDate;
$date2 = date("Y-m-d");
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365 * 60 * 60 * 24));
$months = floor(($diff - ($years * 365 * 60 * 60 * 24)) / ((365 * 60 * 60 * 24) / 12));
$days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
if ($years > 0) {echo $years . " Year";}
if ($years > 1) {echo "s ";}
if ($months > 0) {echo " " . $months . " Month";}
if ($months > 1) {echo "s ";}
if ($date1 == $date2) {echo "1 Day ";}
if ($days > 0) {echo $days . " Day";}
if ($days > 1) {echo "s ";}
}
And this is where $functionDate comes from:
relationshipTimer("2018-04-28");
When you calculate $days, you are assuming that all months are 30 days long, which is obviously wrong. Therefore you get a year that is 11 months plus 35 days (36 days for leap years).
Processing dates is complicated. You should always use specialized tools like PHP's DateTime::diff()
For example, with:
$date1 = new DateTime("2018-04-28");
$date2 = new DateTime("2019-04-27");
$diff = $date2->diff($date1);
print $diff->format("%y years %m months %d days\n");
... you get (because April has 30 days):
0 years 11 months 29 days

Negative hours value in DateInterval::format()

i need to convert number of seconds to date, and then show time difference as days, hours and seconds.
But for some reason after some number of days, in last hour before next full day I get negative hours value. Right now this problem occures if date is greater then 38 days (it's before 1st November). Maybe tomorrow this value will be different, I'm not sure.
Code:
$s = 84600; // 23.5 h in seconds
$s += (60*60*24)*38; // add 38 days in seconds
$d = (new \DateTime())->modify("-".$s."seconds");
echo (new \DateTime())->diff($d)->format("%a days %h:%I");
// shows: 38 days -1:30
Same code with 1 day of difference:
$s = 84600; // 23.5 h in seconds
$s += (60*60*24)*37; // add 37 days in seconds
$d = (new \DateTime())->modify("-".$s."seconds");
echo (new \DateTime())->diff($d)->format("%a days %h:%I");
// shows: 37 days 23:30
PHP version 5.6.2. Tested on localhost, server and http://sandbox.onlinephpfunctions.com/ with same result.
Not sure if you looking for this kind of work around
<?php
$s= 84600;
$ts= strtotime('38 day 30 second', 0);
$difference=$ts-$s;
$days = floor($difference / 86400);
$hours = floor(($difference - $days * 86400) / 3600);
$minutes = floor(($difference - $days * 86400 - $hours * 3600) / 60);
$seconds = floor($difference - $days * 86400 - $hours * 3600 - $minutes * 60);
echo "{$days} days {$hours} hours {$minutes} minutes {$seconds} seconds";
?>
//Output 37 days 0 hours 30 minutes 30 seconds

Converting minutes to hours issue in php

I have this code:
$total_days = 0;
$minutes = 1200;
echo date('H:i', mktime(0, $minutes));
This return me 20 hours, which means two 8 hours + 4 hours working day. It means that in the $total_days will have 2 days + 4 h. How can I divide the 1200 minutes to get 2 days and 4 hours ?
Calculate it manually -
$minutes = 1200;
$total_hours = $minutes / 60;
echo floor($total_hours / 8). ' days ' . ($total_hours % 8). ' hours';
Output
2 days 4 hours
$total_hours contains fractinal value then the calculation should be changed accordingly.

Is there something built into PHP to convert seconds to days, hours, mins?

For example if I have:
$seconds = 3744000; // i want to output: 43 days, 8 hours, 0 minutes
Do I have to create a function to convert this? Or does PHP already have something built in to do this like date()?
function secondsToWords($seconds)
{
$ret = "";
/*** get the days ***/
$days = intval(intval($seconds) / (3600*24));
if($days> 0)
{
$ret .= "$days days ";
}
/*** get the hours ***/
$hours = (intval($seconds) / 3600) % 24;
if($hours > 0)
{
$ret .= "$hours hours ";
}
/*** get the minutes ***/
$minutes = (intval($seconds) / 60) % 60;
if($minutes > 0)
{
$ret .= "$minutes minutes ";
}
/*** get the seconds ***/
$seconds = intval($seconds) % 60;
if ($seconds > 0) {
$ret .= "$seconds seconds";
}
return $ret;
}
print secondsToWords(3744000);
This is very simple and easy to find days , hours, minute and second in core php :
$dbDate = strtotime("".$yourdbtime."");
$endDate = time();
$diff = $endDate - $dbDate;
$days = floor($diff/86400);
$hours = floor(($diff-$days*86400)/(60 * 60));
$min = floor(($diff-($days*86400+$hours*3600))/60);
$second = $diff - ($days*86400+$hours*3600+$min*60);
if($days > 0) echo $days." Days ago";
elseif($hours > 0) echo $hours." Hours ago";
elseif($min > 0) echo $min." Minutes ago";
else echo "Just now";
An easy way to accomplish this nowadays is using DateTimeImmutable, DateInterval and PHP 5.5.0 or higher:
$seconds = 3744000;
$interval = new DateInterval("PT{$seconds}S");
$now = new DateTimeImmutable('now', new DateTimeZone('utc'));
$difference = $now->diff($now->add($interval))->format('%a days, %h hours, %i minutes');
The result will be:
43 days, 8 hours, 0 minutes
The code adds the seconds to a date and calculates the difference to it. Like this, the seconds are transformed into the specified days, hours and minutes.
Warning 1: Working without UTC - Clock changes
You may not specify the DateTimeZone in the constructor of the DateTimeImmutable object to UTC.
$now = new DateTimeImmutable();
There are regions in this world, where the clock changes on specific days of the year. Most countries in the EU change between a summer- and winter-time for example.
If your date interval overlaps the day on that a clock change occurs and your server is set to the related region for that clock change, the result might change as well. This is best shown with the following example:
$twentyFourHours = new DateInterval('PT24H');
$twentyFiveHours = new DateInterval('PT25H');
//Pacific time changed from summer- to winter-time on that day
$summerToWinter = new DateTimeImmutable('2018-11-04');
If you add 24 hours to the $summerToWinter date, you will get the following result:
$extra24Hours = $summerToWinter->add($twentyFourHours);
echo $summerToWinter->format('y-m-d H:i');
echo $extra24Hours->format('y-m-d H:i');
echo $summerToWinter->diff($extra24Hours)->format('%a days, %h hours, %i minutes');
18-11-04 00:00
18-11-04 23:00
0 days, 24 hours, 0 minutes
As you can see, between 00:00 and 23:00 on that day lay 24 hours, which is technically correct. Because of the clock change the timelap between 02:00 and 03:00 occured twice on that day.
Adding 25 hours will result in this:
$extra25Hours = $summerToWinter->add($twentyFiveHours);
echo $summerToWinter->format('y-m-d H:i');
echo $extra25Hours->format('y-m-d H:i');
echo $summerToWinter->diff($extra25Hours)->format('%a days, %h hours, %i minutes');
18-11-04 00:00
18-11-05 00:00
1 days, 0 hours, 0 minutes
As we can see, 1 day elapsed, that has had 25 hours. If this is applied for the 3744000 seconds from the original question, the result would show:
43 days, 7 hours, 0 minutes
The information, that an elapsed day has had 25 hours, is not shown though.
Also, I was not able to recreate the same effect for a day that changes the clock from winter to summer time, that should only elapse 23 hours.
Warning 2: Working with the raw DateInterval object
Using this code without DateTimeImmutable will cause the wrong output:
$seconds = 3744000;
$interval = new DateInterval("PT{$seconds}S");
$difference = $interval->format('%a days, %h hours, %i minutes, %s seconds');
Now, only the seconds are set in the DateInterval object. $difference would be:
(unknown) days, 0 hours, 0 minutes, 3744000 seconds
I like Ian Gregory's answer the most and upvoted it but thought i'd just simplify it a little bit :
function secondsToWords($seconds)
{
$days = intval(intval($seconds) / (3600*24));
$hours = (intval($seconds) / 3600) % 24;
$minutes = (intval($seconds) / 60) % 60;
$seconds = intval($seconds) % 60;
$days = $days ? $days . ' days' : '';
$hours = $hours ? $hours . ' hours' : '';
$minutes = $minutes ? $minutes . ' minutes' : '';
$seconds = $seconds ? $seconds . ' seconds' : '';
return $days . $hours . $minutes . $seconds;
}

Sum of two dates in PHP

how I can sum two dates?
I have two date in this format j h:i:s and I will like to sum them
I found this script but no reference about days and I'm new to this, here is the script, maybe somebody can make the necessary changes.
<?php
/**
* #author Masino Sinaga, http://www.openscriptsolution.com
* #copyright October 13, 2009
*/
echo sum_the_time('01:45:22', '17:27:03'); // this will give you a result: 19:12:25
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}";
}
?>
Usage:
All that I need is to sum two dates from two task like:
Task 1 will take 1 day 10 hour 20 mins 10 sec
Task 2 will take 3 days 17 hours 35 mins 40 sec
so the result will be the total time between task 1 and two
just convert the dates using strtotime and sum the timestamps, than convert to the date again using date function:
$tmstamp = strtotime($date1) + strtotime($date2);
echo date("Y m d", $tmstamp) ;
but why would you add two dates in the first place?
BAsically what they do, is convert hours and minutes into seconds and add those. Then they convert back to hours/minutes.
You simply have to convert days to seconds too:
$seconds += $days * 3600 * 24
and then convert back:
$days = floor($seconds/(3600*24));
$seconds -= $days*3600*24

Categories