As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am wondering what is the most elegant way of calculating a human readable elasped time given a certain amount of seconds. I want to write this in PHP.
Here is the output needed:
elapsedTimeInSeconds > one year, output "# years, # months"
elapsedTimeInSeconds > one month, output "# months, # days"
elapsedTimeInSeconds > one day, output "# days, # hours"
elapsedTimeInSeconds > one hour, output "# hours, # minutes"
elapsedTimeInSeconds > one minute, output "# minutes, # seconds"
I have tried different solutions that are awkward and full of conditional statements, but I was hoping for a more recursive and "clean code" method.
I think this is more flexible, as you can easily add new units like decade, century, etc, and the code wouldn't change:
$names = array("seconds", "minutes", "hours", "days", "months", "years");
$values = array(1, 60, 3600, 24 * 3600, 30 * 24 * 3600, 365 * 24 * 3600);
$time = ...elapsedTimeInSeconds...;
for($i = count($values) - 1; $i > 0 && $time < $values[$i]; $i--);
if($i == 0) {
echo intval($time / $values[$i]) . " " . $names[$i];
} else {
$t1 = intval($time / $values[$i]);
$t2 = intval(($time - $t1 * $values[$i]) / $values[$i - 1]);
echo "$t1 " . $names[$i] . ", $t2 " . $names[$i - 1];
}
Thank you for your suggestions.
I mainly used Waygood and ChrisForrence's suggestions for this method. I tried to keep it as simple as possible and introduced simple arguments such as detail level and delimiter (for string ouput).
public function elapsedTimeHumanReadable($date = null, $detailLevel = 2, $delimiter = ' et ')
{
if($date === null)
{
$date = self::now();
}
$sec = $this->elapsedSecond($date);
$a_sec = 1;
$a_min = $a_sec * 60;
$an_hour = $a_min * 60;
$a_day = $an_hour * 24;
$a_month = $a_day * 30;
$a_year = $a_day * 365;
$text = '';
$resultStack = array();
if($sec >= $a_year)
{
$years = floor($sec / $a_year);
$text .= $years . $this->plural($years, ' an');
$sec = $sec - ($years * $a_year);
array_push($resultStack, $text);
}
if($sec >= $a_month)
{
$months = floor($sec / $a_month);
$text = $months . ' mois';
$sec = $sec - ($months * $a_month);
array_push($resultStack, $text);
}
if($sec >= $a_day)
{
$days = floor($sec / $a_day);
$text = $days . $this->plural($days, ' jour');
$sec = $sec - ($days * $a_day);
array_push($resultStack, $text);
}
if($sec >= $an_hour)
{
$hours = floor($sec / $an_hour);
$text = $hours . $this->plural($hours, ' heure');
$sec = $sec - ($hours * $an_hour);
array_push($resultStack, $text);
}
if($sec >= $a_min)
{
$minutes = floor($sec / $a_min);
$text = $minutes . $this->plural($minutes, ' minute');
$sec = $sec - ($minutes * $a_min);
array_push($resultStack, $text);
}
if($sec >= $a_sec)
{
$seconds = floor($sec / $a_sec);
$text = $sec . $this->plural($seconds, ' seconde');
$sec = $sec - ($sec * $a_sec);
array_push($resultStack, $text);
}
$result = $resultStack[0];
for($i = 1; $i <= $detailLevel - 1; $i++)
{
if(!empty($resultStack[$i]))
{
$result .= $delimiter . $resultStack[$i];
}
}
return $result;
}
I also added a very simple plural function to return the time unit in a correct grammatical fashion:
public function plural($value, $unit)
{
if($value > 1)
{
return $unit . 's';
}
else
{
return $unit;
}
}
I am not really happy with the for loop, but it actually works fine.
Anyway, thank you very much for your help!
I use this:
function durationFormat($time)
{
if(gmdate("Y", $time)>1970) return (1970-gmdate("Y",$time)).gmdate(" \y\r\s ", $time).(gmdate("n",$time)-1).gmdate(" \m\o\n\t\h\s ", $time).(gmdate("j",$time)-1).gmdate(" \d\a\y\s H:i:s", $time);
if(gmdate("n", $time)>1) return (gmdate("n",$time)-1).gmdate(" \m\o\n\t\h\s ", $time).(gmdate("j",$time)-1).gmdate(" \d\a\y\s H:i:s", $time);
if(gmdate("j", $time)>1) return (gmdate("j",$time)-1).gmdate(" \d\a\y\s H:i:s", $time);
return gmdate("H:i:s", $time);
}
It's a bit quick and dirty but does the job
OR
function durationFormat2($seconds)
{
$a_sec=1;
$a_min=$a_sec*60;
$an_hour=$a_min*60;
$a_day=$an_hour*24;
$a_week=$a_day*52;
//$a_month=$a_day*(floor(365/12));
$a_month=$a_day*30;
$a_year=$a_day*365;
$params=2;
$text='';
if($seconds>$a_year)
{
$years=floor($seconds/$a_year);
$text.=$years.' years ';
$seconds=$seconds-($years*$a_year);
$params--;
}
if($params==0) return $text;
if($seconds>$a_month)
{
$months=floor($seconds/$a_month);
$text.=$months.' months ';
$seconds=$seconds-($months*$a_month);
$params--;
}
if($params==0) return $text;
if($seconds>$a_week)
{
$weeks=floor($seconds/$a_week);
$text.=$weeks.' weeks ';
$seconds=$seconds-($months*$a_week);
$params--;
}
if($params==0) return $text;
if($seconds>$a_day)
{
$days=floor($seconds/$a_day);
$text.=$days.' days ';
$seconds=$seconds-($days*$a_day);
$params--;
}
if($params==0) return $text;
$H=gmdate("H", $seconds);
if($H>0)
{
$text.=$H.' hours ';
$params--;
}
if($params==0) return $text;
$M=gmdate("i", $seconds);
if($M>0)
{
$text.=$M.' minutes ';
$params--;
}
if($params==0) return $text;
$S=gmdate("s", $seconds);
$text.=$S.' seconds ';
return $text;
}
Related
I need to add multiple time values as in Hours:mins, so I use
strtotime($value1) + strtotime($value2)
to add all of them, how do I put them back as hours:mins ?
cant use
date("h:i")
it only works if hours < 24.
I appreciate your help. Thanks
Here is an function that will sum all your time values in format HH:MM:
function sum_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 sum_time('01:05', '00:02', '05:59'); # 07:06
demo
Try this :
function time_convert($s) {
$m = 0; $hr = 0; $td = "now";
if ($s > 59) {
$m = (int)($s/60);
$s = $s-($m*60); // sec left over
$td = "$m min";
}
if ($m > 59) {
$hr = (int)($m / 60);
$m = $m - ($hr*60); // min left over
$td = "$hr hr";
if ($hr > 1) {
$td .= "s";
}
if ($m > 0) {
$td .= ", $m min";
}
}
return $td;
}
And use it:
$time = (int) strtotime($v1) + strtotime($v2);
echo time_convert($time);
May it helps
The function strtotime() returns the time in seconds since January 1 1970 00:00:00 UTC. So adding the return value of this function might not do what you would expect.
Instead of using the date functions we can manipulate the string and perform some basic arithmetic operations:
<?php
$value1 = "12:44";
$value2 = "13:47";
$arr1 = explode(':', $value1);
$arr2 = explode(':', $value2);
$totalMinutes = (int)$arr1[0] * 60 + (int)$arr1[1] + (int)$arr2[0] * 60 + (int)$arr2[1];
$hours = (int) ($totalMinutes / 60);
$minutes = $totalMinutes % 60; // Modulus: remainder when dividing with 60
echo $hours . ':' . $minutes;
?>
Another way with DateTime
$dt1 = new DateTime($value1);
$dt2 = new DateTime($value2);
$interval = $dt1->diff($dt2);
echo $interval->format('%a day(s) %h hour(s) %i minute(s)') . '<br />';
echo ($interval->format('%a') * 24 + $interval->format('%h')) . ' hour(s) ';
echo $interval->format('%i minute(s)');
I want to do what StackOverflow is doing which is saying exactly how long it's been since the last post. There is a catch though, SO displays certain information based on how long the ago the last post was - for example, if the post was less than a day ago, they post how many hours ago the last post was; if the post was less than an hour ago they post how many minutes ago it was, etc.
I'm working with a MYSQL DateTime field in the following format:
2012-09-19 13:28:45
I want to compare the above to the time NOW and so I converted that time using PHP's strtotime function and tried comparing the two dates through a function I put together (below). Granted, this is probably the WORST possible way of doing this but after reading about PHP's Date and DateTime functions I'm starting to become very, very confused.
function get_date_format($strToTimeString){
$minute = 60;
$hour = $minutes * 60;
$day = $hour * 24;
$week = $day * 7;
$month = $week * 4;
$year = $month * 12;
$timeNow = strtotime("now");
$timeDiff = $timeNow - $strToTimeString;
if($timeDiff > $minute){
if($timeDiff > $hour){
if($timeDiff > $day){
if($timeDiff > $week){
if($timeDiff > $month){
if($timeDiff > $year){
// Years ago
}
else{
// Months ago
}
}
else{
// Weeks ago
}
}
else{
// Days ago
}
}
else
{
// Hours ago
}
}
else{
// Minutes ago
}
}
else{
// Seconds ago
}
}
Is there a better way to do this? As I mentioned above, I had no luck when trying to use DateTime->diff
I really appreciate any help.
Use DateTime. Here's sample:
$now = new DateTime('now');
$posted = new DateTime($postDateFromDBHere);
$interval = $posted->diff($now);
var_dump($interval);
echo $interval->format('%y-%m-%d %h:%m:%s'); //You can do similar to format your output as you wish.
Use DateTime and DateTime:diff then check each value:
function returnInterval($date){
$datetime1 = new DateTime($date);
$datetime2 = new DateTime();
$diff = $datetime1->diff($datetime2);
$string = '';
$pass = '';
if($diff->y){
$string .= ($diff->y == 1) ? $diff->y." year" : $diff->y." years";
$pass = ', ';
}
if($diff->m){
$string .= $pass;
$string .= ($diff->m == 1) ? $diff->m." month" : $diff->m." months";
$pass = ', ';
}
if($diff->d){
$string .= $pass;
$string .= ($diff->d == 1) ? $diff->d." day" : $diff->d." days";
$pass = ', ';
}
if($diff->h){
$string .= $pass;
$string .= ($diff->h == 1) ? $diff->h." hour" : $diff->h." hours";
$pass = ', ';
}
if($diff->i){
$string .= $pass;
$string .= ($diff->i == 1) ? $diff->i." minute" : $diff->i." minutes";
$pass = ', ';
}
if($diff->s){
$string .= $pass;
$string .= ($diff->s == 1) ? $diff->s." second" : $diff->s." seconds";
}
$pos = strrpos($string, ',');
$string = substr_replace($string, ' and ', $pos, 2);
return $string;
}
echo returnInterval('2012-09-19 13:28:45');
// 8 days, 13 hours, 47 minutes and 44 seconds
After long searching, I got something close to what rottentomatoes used on their forum:
function realTimeSince($time){
define(MINUTE, 60);
define(HOUR, 60*60);
define(DAY, 60*60*24);
define(MONTH, 60*60*24*30);
$delta = strtotime(gmdate("Y-m-d H:i:s", time())) - strtotime($time);
if ($delta < 1 * MINUTE) {
return $delta == 1 ? "one second ago" : $delta . " seconds ago";
}
if ($delta < 2 * MINUTE) {
return "a minute ago";
}
if ($delta < 45 * MINUTE) {
return floor($delta / MINUTE) . " minutes ago";
}
if ($delta < 90 * MINUTE) {
return "an hour ago";
}
if ($delta < 24 * HOUR) {
return floor($delta / HOUR) . " hours ago";
}
if ($delta < 48 * HOUR) {
return "yesterday";
}
if ($delta < 30 * DAY) {
return floor($delta / DAY) . " days ago";
}
if ($delta < 12 * MONTH) {
$months = floor($delta / DAY / 30);
return $months <= 1 ? "one month ago" : $months . " months ago";
} else {
$years = floor($delta / DAY / 365);
return $years <= 1 ? "one year ago" : $years . " years ago";
}
}
so you can use it like this:
realTimeSince('2012-11-12 00:09:54'); //which can be got from a MySQL TIMESTAMP field
modified a little based on http://www.ferdychristant.com/blog//archive/DOMM-7QEFK4
Try the following function
function time_ago($date)
{
//echo "ss";
if (empty($date)) {
return "No date provided";
}
$periods = array("sec", "min", "hr", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
$now = time();
$unix_date = strtotime($date);
// check validity of date
if (empty($unix_date)) {
return "Bad date";
}
// is it future date or past date
if ($now >= $unix_date) {
$difference= $now - $unix_date;
$tense = "ago";
} else {
$difference = $unix_date - $now;
$tense = "from now";
}
for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if ($difference != 1 && $j != 0) {
$periods[$j].= "s";
}
if($difference!=0)
return "$difference $periods[$j] {$tense}";
else
return "a few seconds ago";
}
or
function time_elapsed_since ($postedDateTime){
$time = time() - $postedDateTime; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
time_elapsed_since($postedDateTime).' ago';
This question already has answers here:
Convert seconds to Hour:Minute:Second
(30 answers)
Closed 11 months ago.
Is there a built-in php function that converts number of seconds to military time?
So it will take 3600 and output 01:00:00.
Try this:
<?php
$seconds = 3600;
echo sprintf("%02d:%02d:%02d",$seconds/3600,($seconds/60)%60,$seconds%60);
?>
$seconds = 3600;
echo gmdate('H:i:s', $seconds);
xato was nearly there.
With this approach it's a little bit of a cheat but I believe it will behave in exactly the way that you want it to with hours, minutes and seconds.
edit: and the behaviour will be consistent across all servers regardless of their TZ settings
$seconds = 3600;
echo date('H:i:s', $seconds);
There you go. I might have a use for such a function myself sometime, so I wrote that for you.
function time_format($time) {
if($time > 86400) {
return "more than 1 day";
}
$display = '';
if ($time >= 3600) {
$hours = floor($time/3600);
$time = $time%3600;
if($hours <= 9) { $display .= "0"; }
$display .= $hours;
} else {
$display .= "00";
}
$display .= ":";
if($time >= 60) {
$minutes = floor($time/60);
$time = $time%60;
if($minutes <= 9) { $display .= "0"; }
$display .= $minutes;
} else {
$display .= "00";
}
$display .= ":";
if($time > 0) {
$seconds = $time;
if($seconds <= 9) { $display .= "0"; }
$display .= $seconds;
} else {
$display .= "00";
}
return $display;
}
EDIT: seeing bozdoz's answer makes me feel deeply ashamed :(
Hello i have now search the hole web and found a lot but i just dont know how to make it to work so now im asking here for help
i want to do so then a person create a comment it should said "created 1 sec. ago" and then 1 min and 1 hour and like that :)
can some one help me with that ?
thanks
This is basically human readable format, and can be completed by mathematical checks to check the distance of times, working snippet below:
function RelativeTime($timestamp)
{
$difference = time() - $timestamp;
$periods = array("sec", "min", "hour", "day", "week", "month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
if ($difference > 0)
{
$ending = "ago";
}
else
{
$difference = -$difference;
$ending = "to go";
}
for($j = 0; $difference >= $lengths[$j]; $j++)
{
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1)
{
$periods[$j].= "s";
}
return $difference . $periods[$j] . $ending;
}
This will do future timestamps such as 12 days to go aswell as timestamps such as 12 days ago
Hope this helps.
Original Source: http://blog.evandavey.com/2008/04/php-date-in-human-readable-form-facebook-style.html
I think this is exactly what you want. When you using the function set $deep parameter to 1.
function timespan($seconds = 1, $time = '', $deep = NULL)
{
$CI = & get_instance();
$CI->lang->load('date');
$current_deep = 0;
if (!is_numeric($seconds))
{
$seconds = 1;
}
if (!is_numeric($time))
{
$time = time();
}
if ($time <= $seconds)
{
$seconds = 1;
}
else
{
$seconds = $time - $seconds;
}
$str = '';
$years = floor($seconds / 31536000);
if ($years > 0)
{
$str .= $years . ' ' . $CI->lang->line((($years > 1) ? 'date_years' : 'date_year')) . ', ';
if (++$current_deep == $deep)
return substr(trim($str), 0, -1);
}
$seconds -= $years * 31536000;
$months = floor($seconds / 2628000);
if ($years > 0 OR $months > 0)
{
if ($months > 0)
{
$str .= $months . ' ' . $CI->lang->line((($months > 1) ? 'date_months' : 'date_month')) . ', ';
if (++$current_deep == $deep)
return substr(trim($str), 0, -1);
}
$seconds -= $months * 2628000;
}
$weeks = floor($seconds / 604800);
if ($years > 0 OR $months > 0 OR $weeks > 0)
{
if ($weeks > 0)
{
$str .= $weeks . ' ' . $CI->lang->line((($weeks > 1) ? 'date_weeks' : 'date_week')) . ', ';
if (++$current_deep == $deep)
return substr(trim($str), 0, -1);
}
$seconds -= $weeks * 604800;
}
$days = floor($seconds / 86400);
if ($months > 0 OR $weeks > 0 OR $days > 0)
{
if ($days > 0)
{
$str .= $days . ' ' . $CI->lang->line((($days > 1) ? 'date_days' : 'date_day')) . ', ';
if (++$current_deep == $deep)
return substr(trim($str), 0, -1);
}
$seconds -= $days * 86400;
}
$hours = floor($seconds / 3600);
if ($days > 0 OR $hours > 0)
{
if ($hours > 0)
{
$str .= $hours . ' ' . $CI->lang->line((($hours > 1) ? 'date_hours' : 'date_hour')) . ', ';
if (++$current_deep == $deep)
return substr(trim($str), 0, -1);
}
$seconds -= $hours * 3600;
}
$minutes = floor($seconds / 60);
if ($days > 0 OR $hours > 0 OR $minutes > 0)
{
if ($minutes > 0)
{
$str .= $minutes . ' ' . $CI->lang->line((($minutes > 1) ? 'date_minutes' : 'date_minute')) . ', ';
if (++$current_deep == $deep)
return substr(trim($str), 0, -1);
}
$seconds -= $minutes * 60;
}
if ($str == '')
{
$str .= $seconds . ' ' . $CI->lang->line((($seconds > 1) ? 'date_seconds' : 'date_second')) . ', ';
}
return substr(trim($str), 0, -1);
}
Source
Assuming you have the difference $now - $creation_time in seconds, a way to do it is to divide it by X seconds (1 minute = 60, 1 hour = 3600, 1 day = 86400) starting with the largest number to see how many of those units fit in your creation time, then use its remainder to try and fit the smaller units in.
$diffSeconds = time() - $creation_time ;
$numDays = $diffSeconds / 86400 ;
$remainderDaySeconds = $diffSeconds % 86400 ;
$numHours = $remainderDaySeconds / 3600 ;
$remainderSeconds = $remainderDaySeconds % 3600 ;
The modulo operator % will give you the remainder of a division. This way, if a post was created less than a day ago then $numDays is 0 and $remainderDaySeconds is $diffSeconds, so you can check and print out accordingly.
Edit I got curious and looked in SO, turns out there are quite a few questions expanding on this. Linking some:
Calculate relative time in C#
calculating and showing a date as 'secs ago', 'mins ago', 'hours ago' etc which points to http://www.php.net/manual/en/function.time.php#89415
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);