I'm trying to calculate the time difference (in hours) between two times inputted via a timepicker. I have working JavaScript code, but would rather use server side code to make this calculation as it's quite important. If you want me to post the working JS code let me know in comments.
Calculating the difference between the times is easy enough, but I require the output in a particular format. For example inputs of '07:30' and '14:00' would return 6.5 rather than 6.3. The reason for this is to make it easier for me to use this time difference in calculations.
PHP Code i've tried:
Attempt #1:
<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);
echo $time_diff->format('%h.%i');
?>
Returns 6.3 as expected.
Attempt #2:
<?php
$start_time = "07:30";
$end_time = "14:00";
$start_time = str_replace(":", "", $start_time);
$end_time = str_replace(":", "", $end_time);
$res = $end_time - $start_time;
$result = $res / 100;
echo $result;
?>
Returns 6.7.
Tool used to test output: http://codepad.viper-7.com/
Just extract the minutes:
<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);
$hours = (int)$time_diff->format('%h');
$hour_part = ((int)$time_diff->format('%i')) / 60;
echo $hours + $hour_part;
?>
Make sure to change the type to (int) before any calculations.
If you divide the minutes by 60 you will get what part of a hour they represent.
<?php
$start_time = new DateTime('07:30');
$end_time = new DateTime('14:00');
$time_diff = date_diff($start_time,$end_time);
echo $time_diff->format('%h') + $time_diff->format('%i')/60;
?>
Returns 6.5 as expected.
You can try this:
<?php
$start_time = strtotime("07:30");
$end_time = strtotime("14:00");
$diff = $end_time - $start_time;
echo $diff;
1 hour = 60 min.
Demo.
$start_time = "07:30";
$end_time = "14:00";
list($h1, $m1) = explode(':', $start_time);
list($h2, $m2) = explode(':', $end_time);
// 1 hr = 60 min
$res = ($h2*60 - $m2) - ($h1*60 + $m1);
$result = floor($res/60) .'.'. $res % 60;
echo $result;
Try this
function time_difference($time1, $time2) {
$time1 = strtotime("1980-01-01 $time1");
$time2 = strtotime("1980-01-01 $time2");
if ($time2 < $time1) {
$time2 += 86400;
}
return date("H:i:s", strtotime("1980-01-01 00:00:00") + ($time2 - $time1));
}
echo time_difference("11:30:30", "22:40:59");
You can use this function to get the time difference between two times:
function timeBetween($start_date,$end_date)
{
$diff = $end_date-$start_date;
$seconds = 0;
$hours = 0;
$minutes = 0;
if($diff % 86400 <= 0){$days = $diff / 86400;} // 86,400 seconds in a day
if($diff % 86400 > 0)
{
$rest = ($diff % 86400);
$days = ($diff - $rest) / 86400;
if($rest % 3600 > 0)
{
$rest1 = ($rest % 3600);
$hours = ($rest - $rest1) / 3600;
if($rest1 % 60 > 0)
{
$rest2 = ($rest1 % 60);
$minutes = ($rest1 - $rest2) / 60;
$seconds = $rest2;
}
else{$minutes = $rest1 / 60;}
}
else{$hours = $rest / 3600;}
}
if($days > 0){$days = $days.' days, ';}
else{$days = false;}
if($hours > 0){$hours = $hours.' hours, ';}
else{$hours = false;}
if($minutes > 0){$minutes = $minutes.' minutes, ';}
else{$minutes = false;}
$seconds = $seconds.' seconds';
return $days.''.$hours.''.$minutes.''.$seconds;
}
Related
i have two time values as give below
$time = 06:58:00;
$time2 = 00:40:00;
I am doing this for calculating the appointments and available time for a particular user
so i tried in this way
$max_date=abs(strtotime($time) + strtotime($time2));
but it is returning $max_date =2673452280
any suggestions pls
this code sample would take hour in $time and add the hour in $time2 to it
for example: time=06:58:00, time2=00:40:00, result = 07:38:00
$time = "06:58:00";
$time2 = "00:40:00";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
Use this function...
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;
if($seconds < 9)
{
$seconds = "0".$seconds;
}
if($minutes < 9)
{
$minutes = "0".$minutes;
}
if($hours < 9)
{
$hours = "0".$hours;
}
return "{$hours}:{$minutes}:{$seconds}";
}
strtotime function takes full-date as an argument and valid format are as following:
http://www.php.net/manual/en/datetime.formats.php
You can see that in online PHP manual for the function at http://php.net/manual/en/function.strtotime.php
If you're build those time strings from a database before, you'd probably want to rebuild them to something like this:
$time = "00:06:58";
$time2 = "40 minutes";
$timestamp = strtotime($time." +".$time2);
$endTime = date("d.m.Y H:i:s", $timestamp);
Easiest way to add two times using php is :
1) Convert time from H:i:s (e.g. 08:15:40) format to seconds.
2) do the same for second time value ref:step 1
3) add converted values and store it php variable
4) Now convert total (which is in seconds) to H:i:s
and it works for me.
PHP Script:
$str_time ="08:04:40";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_old_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$str_time ="02:10:22";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_toadd_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$hrs_old_int1 = $hrs_old_seconds + $hrs_toadd_seconds;
echo $Total=gmdate("H:i:s", $hrs_old_int1);
Result= :10:15:02
Anudeep's solution was great for my use case, but I needed to be able to add negative times as well. Here's a slightly edited version of his code to take and return negative time strings ("-01:01:01" for example):
public static function sum_the_times($time1, $time2)
{
$times = array($time1, $time2);
$seconds = 0;
$negative = false;
foreach ($times as $time) {
list($hour,$minute,$second) = explode(':', $time);
if(substr($hour,0,1) == '-'){
$seconds -= substr($hour,1)*3600;
$seconds -= $minute*60;
$seconds -= $second;
} else {
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
}
if (substr($seconds, 0, 1) == '-') {
$negative = true;
$seconds = ($seconds * -1);
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if ($seconds < 9) {
$seconds = "0".$seconds;
}
if ($minutes < 9) {
$minutes = "0".$minutes;
}
if ($hours < 9) {
$hours = "0".$hours;
}
return ($negative ? "-" : "")."{$hours}:{$minutes}:{$seconds}";
}
You can try this
$time = "04:00:00";
$time2 = "03:30:00";
$result = date("H:i:s",strtotime($time)+strtotime($time2));
echo $result;
It gives output 07:30:00 but it does not work sometime in different version of operating system. If you want to get sum of time then you can use this code
<?php
function CalculateTime($time1, $time2) {
$time1 = date('H:i:s',strtotime($time1));
$time2 = date('H:i:s',strtotime($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;
if($seconds < 9)
{
$seconds = "0".$seconds;
}
if($minutes < 9)
{
$minutes = "0".$minutes;
}
if($hours < 9)
{
$hours = "0".$hours;
}
return "{$hours}:{$minutes}:{$seconds}";
}
$time1= '23:32:05';
$time2 = '01:29';
echo CalculateTime($time1,$time2);
?>
In the second code, you can send time in hour:minutes or hours:minutes:seconds. This code accept both format because it convert time automatically
Here's a version that will cater for over 24 hours and doesn't use strtotime:
$time0 = "24:01:02";
$time1 = "01:02:03";
$matches0 = explode(':',$time0); // split up the string
$matches1 = explode(':',$time1);
$sec0 = $matches0[0]*60*60+$matches0[1]*60+$matches0[2];
$sec1 = $sec0+ $matches1[0]*3600+$matches1[1]*60+$matches1[2]; // get total seconds
$h = intval(($sec1)/3600);
$m = intval(($sec1-$h*3600)/60);
$s = $sec1-$h*3600-$m*60;
echo $str = str_pad($h, 2, '0', STR_PAD_LEFT).':'.str_pad($m, 2, '0', STR_PAD_LEFT).':'.str_pad($s, 2, '0', STR_PAD_LEFT);
I have a php timestamp 1331875634 generated using php time() function.
I have the current timestamp generated using same function.
<?php
$time1 = "1331875634";
$time2 = time();
echo $differencem; //time difference in minutes
echo $differenceh; //time difference in hours
?>
I want to know the difference between these two in minutes. The minutes may be divided by 60 to make it in hours.
You get the different in seconds if you subtract them, so divide it by 60 to get minutes and by 60 again to get hours.
I created this code to take standard PHP UNIX TIMESTAMP, calculate the difference in time and return a standard time or a specialized time format. This is great for timing a project and calculating the time it takes to get the results.
function timerFormat($start_time, $end_time, $std_format = false)
{
$total_time = $end_time - $start_time;
$days = floor($total_time /86400);
$hours = floor($total_time /3600);
$minutes = intval(($total_time/60) % 60);
$seconds = intval($total_time % 60);
$results = "";
if($std_format == false)
{
if($days > 0) $results .= $days . (($days > 1)?" days ":" day ");
if($hours > 0) $results .= $hours . (($hours > 1)?" hours ":" hour ");
if($minutes > 0) $results .= $minutes . (($minutes > 1)?" minutes ":" minute ");
if($seconds > 0) $results .= $seconds . (($seconds > 1)?" seconds ":" second ");
}
else
{
if($days > 0) $results = $days . (($days > 1)?" days ":" day ");
$results = sprintf("%s%02d:%02d:%02d",$results,$hours,$minutes,$seconds);
}
return $results;
}
Example:
$begin_routine_time = time();
echo(timerFormat($begin_routine_time, $time()));
$datetime1 = new DateTime(date('Y-m-d H:i:s', 1331875634));
$datetime2 = new DateTime(date('Y-m-d H:i:s'));
$oDiff = $datetime1->diff($datetime2);
echo $oDiff->y.' Years <br/>';
echo $oDiff->m.' Months <br/>';
echo $oDiff->d.' Days <br/>';
echo $oDiff->h.' Hours <br/>';
echo $oDiff->i.' Minutes <br/>';
echo $oDiff->s.' Seconds <br/>';
Once I needed to convert seconds to time like 1 day 03:34:13 days hours:minuts:secondes
I wrote this function
function sECONDS_TO_HMS($seconds)
{
$days = floor($seconds/86400);
$hrs = floor($seconds/3600);
$mins = intval(($seconds / 60) % 60);
$sec = intval($seconds % 60);
if($days>0){
//echo $days;exit;
$hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
$hours=$hrs-($days*24);
$return_days = $days." Days ";
$hrs = str_pad($hours,2,'0',STR_PAD_LEFT);
}else{
$return_days="";
$hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
}
$mins = str_pad($mins,2,'0',STR_PAD_LEFT);
$sec = str_pad($sec,2,'0',STR_PAD_LEFT);
return $return_days.$hrs.":".$mins.":".$sec;
}
echo sECONDS_TO_HMS(65); // 00:01:05
echo sECONDS_TO_HMS(76325); //21:12:05
echo sECONDS_TO_HMS(345872); // 4 Days 00:04:32
I think it could be helpful for you.
My output is in the format of 290.52262423327 seconds. How can i change this to 00:04:51?
The same output i want to show in seconds and in HH:MM:SS format, so if it is seconds, i want to show only 290.52 seconds.(only two integers after decimal point)? how can i do this?
I am working in php and the output is present in $time variable. want to change this $time into $newtime with HH:MM:SS and $newsec as 290.52.
Thanks :)
1)
function foo($seconds) {
$t = round($seconds);
return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}
echo foo('290.52262423327'), "\n";
echo foo('9290.52262423327'), "\n";
echo foo(86400+120+6), "\n";
prints
00:04:51
02:34:51
24:02:06
2)
echo round($time, 2);
Try this one
echo gmdate("H:i:s", 90);
For till 23:59:59 hours you can use PHP default function
echo gmdate("H:i:s", 86399);
Which will only return the result till 23:59:59
If your seconds is more then 86399 than
with the help of #VolkerK answer
$time = round($seconds);
echo sprintf('%02d:%02d:%02d', ($time/3600),($time/60%60), $time%60);
will be the best options to use ...
Edit: A comment pointed out that the previous answer fails if the number of seconds exceeds a day (86400 seconds). Here's an updated version. The OP did not specify this requirement so this may be implemented differently than the OP might expect, and there may be much better answers here already. I just couldn't stand having provided an answer with this bug.
$iSecondsIn = 290.52262423327;
// Account for days.
$iDaysOut = 0;
while ($iSecondsIn >= 86400) {
$iDaysOut += 1;
$iSecondsIn -= 86400;
}
// Display number of days if appropriate.
if ($iDaysOut > 0) {
print $iDaysOut.' days and ';
}
// Print the final product.
print date('H:i:s', mktime(0, 0, $iSecondsIn));
The old version, with the bug:
$iSeconds = 290.52262423327;
print date('H:i:s', mktime(0, 0, $iSeconds));
Try this:
$time = 290.52262423327;
echo date("h:i:s", mktime(0,0, round($time) % (24*3600)));
Based on https://stackoverflow.com/a/3534705/4342230, but adding days:
function durationToString($seconds) {
$time = round($seconds);
return sprintf(
'%02dD:%02dH:%02dM:%02dS',
$time / 86400,
($time / 3600) % 24,
($time / 60) % 60,
$time % 60
);
}
I dont know if this is the most efficient way, but if you also need to display days, this works:
function foo($seconds) {
$t = round($seconds);
return sprintf('%02d %02d:%02d:%02d', ($t/86400%24), ($t/3600) -(($t/86400%24)*24),($t/60%60), $t%60);
}
Try this :)
private function conversionTempsEnHms($tempsEnSecondes)
{
$h = floor($tempsEnSecondes / 3600);
$reste_secondes = $tempsEnSecondes - $h * 3600;
$m = floor($reste_secondes / 60);
$reste_secondes = $reste_secondes - $m * 60;
$s = round($reste_secondes, 3);
$s = number_format($s, 3, '.', '');
$h = str_pad($h, 2, '0', STR_PAD_LEFT);
$m = str_pad($m, 2, '0', STR_PAD_LEFT);
$s = str_pad($s, 6, '0', STR_PAD_LEFT);
$temps = $h . ":" . $m . ":" . $s;
return $temps;
}
Personally, going off other peoples answers I made my own parser.
Works with days, hours, minutes and seconds. And should be easy to expand to weeks/months etc.
It works with deserialisation to c# as well
function secondsToTimeInterval($seconds) {
$t = round($seconds);
$days = floor($t/86400);
$day_sec = $days*86400;
$hours = floor( ($t-$day_sec) / (60 * 60) );
$hour_sec = $hours*3600;
$minutes = floor((($t-$day_sec)-$hour_sec)/60);
$min_sec = $minutes*60;
$sec = (($t-$day_sec)-$hour_sec)-$min_sec;
return sprintf('%02d:%02d:%02d:%02d', $days, $hours, $minutes, $sec);
}
1)
$newtime = sprintf( "%02d:%02d:%02d", $time / 3600, $time / 60 % 60, $time % 60 );
2)
$newsec = sprintf( "%.2f", $time );
If you're using Carbon (such as in Laravel), you can do this:
$timeFormatted = \Carbon\Carbon::now()->startOfDay()->addSeconds($seconds)->toTimeString();
But $timeFormatted = date("H:i:s", $seconds); is probably good enough.
Just see caveats.
Here was my implementation with microseconds
/**
* #example 00 d 00 h 00 min 00 sec 005098 ms (0.005098 sec.ms)
*/
public function __toString()
{
// Add your code to get $seconds and $microseconds
$time = round(($seconds + $microseconds), 6, PHP_ROUND_HALF_UP);
return sprintf(
'%02d d %02d h %02d min %02d sec %06d ms (%s sec.ms)',
$time / 86400,
($time / 3600) % 24,
($time / 60) % 60,
$time % 60,
$time * 1000000 % 1000000,
$time
);
}
echo date('H:i:s', round($time)%86400);
Simple formatter with progressively added parts - sample:
formatTime(123) => 2m 3s
formatTime(7400) => 2h 3m 20s
formatTime(999999) => 11d 13h 46m 39s
function formatTime($secs)
{
$secs = max(0, intval($secs));
if($secs > 0){
$out = [];
$yrs = floor($secs / 31536e3);
if($yrs){
$out[] = $yrs."y";
}
$rem = $secs - $yrs * 31536e3;
$days = floor($rem / 86400);
if($days || $out){
$out[] = $days."d";
}
$rem -= $days * 86400;
$hrs = floor($rem / 3600);
if($hrs || $out){
$out[] = $hrs."h";
}
$rem -= $hrs * 3600;
$min = floor($rem / 60);
if($min || $out){
$out[] = $min."m";
}
$rem -= $min * 60;
$out[] = $rem."s";
return implode(" ", $out);
}
return 0;
}
echo date('H:i:s',$time);
echo number_format($time,2);
Numero uno... http://www.ckorp.net/sec2time.php (use this function)
Numero duo... echo round(290.52262423327,2);
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);
How could set a date and get a countdown in PHP? For example if I set the date as 3 December 2PM it would tell me how many days and hours are remaining.
No need for user inputs for the date as it will be hard coded.
Thanks.
You can use the strtotime function to get the time of the date specified, then use time to get the difference.
$date = strtotime("December 3, 2009 2:00 PM");
$remaining = $date - time();
$remaining will be the number of seconds remaining. Then you can divide that number to get the number of days, hours, minutes, etc.
$days_remaining = floor($remaining / 86400);
$hours_remaining = floor(($remaining % 86400) / 3600);
echo "There are $days_remaining days and $hours_remaining hours left";
Let me play around like this:
$rem = strtotime('2012-08-01 14:00:00') - time();
$day = floor($rem / 86400);
$hr = floor(($rem % 86400) / 3600);
$min = floor(($rem % 3600) / 60);
$sec = ($rem % 60);
if($day) echo "$day Days ";
if($hr) echo "$hr Hours ";
if($min) echo "$min Minutes ";
if($sec) echo "$sec Seconds ";
echo "Remaining...";
Try this at your leisure... :-)
NOTE: There is no if() test for echo "Remaining...", just coz you wont process this in case when $rem <= 0. Isn't it?
PHP 5.3 allows this:
$dt_end = new DateTime('December 3, 2009 2:00 PM');
$remain = $dt_end->diff(new DateTime());
echo $remain->d . ' days and ' . $remain->h . ' hours';
It's not as trivial as subtracting strtotime() results, since there are daylight savings and time would be mathematically correct, but not physically. Anyway, for these purposes you should use gmdate() function, which has no daylight savings:
$date = gmdate('U', strtotime('2009-12-03 14:00'));
// Get difference between both dates without DST
$diff = $date - gmdate('U');
// Days (in last day it will be zero)
$diff_days = floor($remaining / (24 * 60 * 60));
// Hours (in the last hour will be zero)
$diff_hours = floor($remaining % (24 * 60 * 60) / 3600);
Using #Izhar Aazmi solution, you could set this up nicely for display, as such:
public function countdown($time, $h = true, $m = true, $s = true) {
$rem = $time - time();
$day = floor($rem / 86400);
$hr = floor(($rem % 86400) / 3600);
$min = floor(($rem % 3600) / 60);
$sec = ($rem % 60);
if ( $day && !$h ) {
if ( $hr > 12 ) $day++; // round up if not displaying hours
}
$ret = Array();
if ( $day && $h ) $ret[] = ($day ? $day ." day".($day==1?"":"s") : "");
if ( $day && !$h ) $ret[] = ($day ? $day . " day" . ($day == 1 ? "" : "s") : "");
if ( $hr && $h ) $ret[] = ($hr ? $hr ." hour" . ($hr==1?"":"s") : "");
if ( $min && $m && $h ) $ret[] = ($min ? $min ." minute". ($min==1?"":"s") : "");
if ( $sec && $s && $m && $h ) $ret[] = ($sec ? $sec ." second".($sec==1?"":"s") : "");
$last = end($ret);
array_pop($ret);
$string = join(", ", $ret)." and {$last}";
return $string;
}
I hope this helps! It's a nice clean way or displaying the countdown.
Did this countdown until the end of the semester:
$endOfSemester = mktime(15,30,0,5,21,2015);
$now = time();
$secondsRemaining = $endOfSemester - $now;
define('SECONDS_PER_MINUTE', 60);
define('SECONDS_PER_HOUR', 3600);
define('SECONDS_PER_DAY', 86400);
$daysRemaining = floor($secondsRemaining / SECONDS_PER_DAY); //days until end
$secondsRemaining -= ($daysRemaining * SECONDS_PER_DAY); //update variable
$hoursRemaining = floor($secondsRemaining / SECONDS_PER_HOUR); //hours until end
$secondsRemaining -= ($hoursRemaining * SECONDS_PER_HOUR); //update variable
$minutesRemaining = floor($secondsRemaining / SECONDS_PER_MINUTE); //minutes until end
$secondsRemaining -= ($minutesRemaining * SECONDS_PER_MINUTE); //update variable
echo("<h3>There are $daysRemaining days, $hoursRemaining hours, $minutesRemaining minutes, $secondsRemaining seconds until the end of the semester</h3>"); //print message
For those looking for a function capable of handling larger and smaller time span (php >5.3) :
/**
* Return a textual representation of the time left until specified date
*/
function timeleft(DateTime $date){
$now = new DateTime();
if($now > $date){
return '0 second';
}
$interval = $date->diff($now);
if($interval->y){
return $interval->format("%y year").($interval->y > 1 ? 's':'');
} else if($interval->m){
return $interval->format("%m month").($interval->m > 1 ? 's':'');
} else if($interval->d){
return $interval->format("%d day").($interval->d > 1 ? 's':'');
} else if($interval->h){
return $interval->format("%h hour").($interval->h > 1 ? 's':'');
} else if($interval->i){
return $interval->format("%i minute").($interval->i > 1 ? 's':'');
} else if($interval->s) {
return $interval->format("%s second").($interval->s > 1 ? 's':'');
} else {
return 'milliseconds';
}
}