How to get total minutes to display as Xhrs, Xmin? - php

I'm taking a total number of minutes and am trying to calculate total hrs & minutes.
If you do:
$elapsed = "6476"; // Trying to get 107:56 (107 hours, 56 min)
if ($elapsed > 60) { $format = "i:s"; }
if ($elapsed > 3600) { $format = "H:i:s"; }
$showdiff = gmdate($format, $elapsed);
The problem with this is it doesn't work for calculations above 23hrs 59min.
So, you can do simple division:
$elapsed = $elapsed / 60; // total hours
Only then you will get a fraction (in this case, 107.933333333). I need to keep this as hours and minutes. Any suggestions?

You should be able to use division (as you've stated) and modulus division to accomplish what you want.
$hours = floor($elapsed / 60);
$minutes = round(($elapsed / 60) % 60);
echo $hours . "hrs " . $minutes . "min";

you could try
$elapsed = $elapsed / 60; // total hours (107.933333333)
$parts = explode(".", $elapsed); // split 107.93333 into 2 parts using the . as a separator
$minutes = $parts[1] // $parts[0] is 107, this will be the .9333
$minutes = $minutes * 60 // = 55.99...
$minutes = round($minutes); // round 55.9999 up to 56
$hours = $parts[0];
echo "$hours hrs $minutes mins";
probably could be written a bit better but my excuse is I'm tired :)
That should give you an idea though and let you do what you need to.

Related

Laravel Convert seconds into days hours and minutes

I have to implement some functionality using time calculation and my app has following type of code.
date_default_timezone_set(auth()->user()->timezone);
$t_now = \Carbon\Carbon::parse(date('Y-m-d H:i:s'));
$t_allowed = \Carbon\Carbon::parse($shift_details->start_time) ;
#endphp
#php
$check = $t_allowed->diffForHumans($t_now);
$search = 'after';
$dff_min = $t_allowed->diffInSeconds($t_now, true);
$init = $dff_min;
$day = floor($init / 86400);
$hours = floor(($init - $day * 86400) / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;
$late_not_late = $hours . ' hours ' . $minutes . ' minutes ' . $seconds . ' seconds ';
first i want to confirm that $dff_min = $t_allowed->diffInSeconds($t_now, true); is returning minutes or seconds? Acording to my knowledge $dff_min contain seconds
i know that hours could be calculate using (init /3600) but what is the meaning of following statement
$hours = floor(($init - $day * 86400) / 3600);
why developer subtracting $day * 86400 from $init?
similary we also can calculate seconds by $init/60 since in one minute there are 60 seconds but
what is meaning of following line
$minutes = floor(($init / 60) % 60);
and also why he is using Modulo here
$seconds = $init % 60;
\Carbon\Carbon::parse(date('Y-m-d H:i:s')) will call twice the timelib and will loose the microseconds, just do \Carbon\Carbon::now() and you don't need to reinvent the wheel, you can get this exact string with:
$t_now = \Carbon\Carbon::now();
$t_allowed = \Carbon\Carbon::parse($shift_details->start_time);
$late_not_late = $t_allowed->diffForHumans($t_now, ['parts' => 3, 'syntax' => CarbonInterface::DIFF_ABSOLUTE]);
$late_not_late will contain 2 days 9 hours 20 minutes

How to Round Up to the nearest 15 minutes in PHP [duplicate]

This is not a duplicate question, but involves a little understanding about time.
I need a solution to the following problem
I have a number of specifically produced times (based on a date), that need to be rounded to the nearest 15 secs:
60 secs is 1 minute
meaning a regular round, floor, ceiling is to the nearest decimal (10/5)
which doesn't help me with time.
also since I'm dealing with secs, it could be that 59:59 will be rounded up to the nearest hour: e.g. 17:59:59 should be 18:00.
example:
6:17:29 rounded to 6:17:30
6:29:55 rounded to 6:30:00
20:45:34 rounded to 20:45:30
The following code does some of the job:
$hr = date('H',($resultStr));
$mn = date('i',($resultStr));
$sc = date('s',($resultStr));
$tot = ($hr * 60 * 60) + ($mn * 60) + $sc;
$totd = $tot / (60);
$totc = ceil($totd);
$totc = $totc / 60;
$hr = floor($totc);
$mn = ($totc - $hr)*60;
$mnflr = floor($mn);
$mn2 = $mn - $mnflr;
echo "$hr:$mnflr";
This results in:
18:35:17 rounded to: 18:36 (which is wrong)
18:31:49 rounded to: 18:32 (which is wrong)
As an aside:
$secs = date('U',($resultStr));
$round = ceil ( (($secs / 60 ) * 60 ));
$newtime = date('H:i:s',($round));
produces: 18:42:58 rounded to: 18:42:58 which is also incorrect
Please and thank you in advance....
You're massively overcomplicating this, just do rounding on the Unix timestamp level:
function roundMyTime($time)
{
$time = strtotime($time);
$time = 15*round($time/15);
echo date('H:i:s', $time)."\n";
}
roundMyTime('18:35:17');
roundMyTime('18:35:27');
roundMyTime('18:35:37');
roundMyTime('18:35:47');
roundMyTime('18:35:57');
roundMyTime('18:36:07');
roundMyTime('18:36:17');
Outputs:
18:35:15
18:35:30
18:35:30
18:35:45
18:36:00
18:36:00
18:36:15
Demo here.
$seconds = ($hr * 60 + $mn) * 60 + $sc; // convert to seconds
$rounded = round($seconds/15)*15; // round
$sc = $rounded % 60; // get seconds
$mn = ($rounded - $sc) / 60 % 60; // get minutes
$hr = ($rounded - $sc - $mn * 60) / 60; // get hours
Convert the date to seconds using strtotime and then just work in seconds.
$seconds = strtotime($date);
$seconds /= 15;
$seconds = round($seconds);
$seconds *= 15;
$date = date("Y-m-d H:i:s", $seconds);

How to convert given seconds to hours minutes seconds format in php in custom way?

I will get random number of seconds the number may greater than 86400 which is greater than 24hours (when converts to hours) so php gmdate() won't get my required output. So I created the following code.
$ts = mt_rand(36000,99999);
echo floor($ts/3600)."Hr ".floor(($ts/3600 - floor($ts/3600))*60)."min ".round(((($ts/3600 - floor($ts/3600))*60) - floor(($ts/3600 - floor($ts/3600))*60))*60)."sec";
I am getting the output like 22Hr 29min 4sec for $ts = 80944;
Everything is fine but for $ts = 39540; the output came is 10Hr 58min 60sec here 60sec came which is wrong. it should get like 10Hr 59min 0sec. What's wrong in my code?
I didn't break your code apart to find out what was wrong, but I believe this solves the problem.
$ts = mt_rand(36000,99999);
$h = floor($ts / 3600);
$m = floor(($ts - 3600 * $h) / 60);
$s = $ts - ($h * 3600) - ($m * 60);
echo $h . "Hr " . $m . "Min " . $s . "s";
I have modified the code to check if the value of secs is 60, as It is already being caluculated due to round while calculating minutes
$ts = 80944; //mt_rand(36000,99999);
echo floor($ts/3600)."Hr ". round(($ts/3600 - floor($ts/3600))*60)."min ";
echo (round(((($ts/3600 - floor($ts/3600))*60) - floor(($ts/3600 - floor($ts/3600))*60))*60) == 60) ? '0' : round(((($ts/3600 - floor($ts/3600))*60) - floor(($ts/3600 - floor($ts/3600))*60))*60)."sec";
Hey you can do it with a modulo calculation :
$secondsGiven = 1036899;
$outputSeconds = $secondsGiven % 60;
$minutes = ($secondsGiven-$outputSeconds) / 60 ;
$outputMinutes = $minutes % 60;
$hours = ($minutes - $outputMinutes) / 60;
$outputHours= $hours % 24;
$outputDays = $outputHours / 24;
echo $outputDays . 'Days ' . $outputHours . 'HR ' . $outputMinutes . 'min ' . $outputSeconds . 'sec';
this example would output : 12Days 0Hr 1min 39sec
echo gmdate("H:i:s", 39540);
use this

How to convert a decimal into time, eg. HH:MM:SS

I am trying to take a decimal and convert it so that I can echo it as hours, minutes, and seconds.
I have the hours and minutes, but am breaking my brain trying to find the seconds. Been googling for awhile with no luck. I'm sure it is quite simple, but nothing I have tried has worked. Any advice is appreciated!
Here is what I have:
function convertTime($dec)
{
$hour = floor($dec);
$min = round(60*($dec - $hour));
}
Like I said, I get the hour and minute without issue. Just struggling to get seconds for some reason.
Thanks!
If $dec is in hours ($dec since the asker specifically mentioned a decimal):
function convertTime($dec)
{
// start by converting to seconds
$seconds = ($dec * 3600);
// we're given hours, so let's get those the easy way
$hours = floor($dec);
// since we've "calculated" hours, let's remove them from the seconds variable
$seconds -= $hours * 3600;
// calculate minutes left
$minutes = floor($seconds / 60);
// remove those from seconds as well
$seconds -= $minutes * 60;
// return the time formatted HH:MM:SS
return lz($hours).":".lz($minutes).":".lz($seconds);
}
// lz = leading zero
function lz($num)
{
return (strlen($num) < 2) ? "0{$num}" : $num;
}
Very simple solution in one line:
echo gmdate('H:i:s', floor(5.67891234 * 3600));
Everything upvoted didnt work in my case.
I have used that solution to convert decimal hours and minutes to normal time format.
i.e.
function clockalize($in){
$h = intval($in);
$m = round((((($in - $h) / 100.0) * 60.0) * 100), 0);
if ($m == 60)
{
$h++;
$m = 0;
}
$retval = sprintf("%02d:%02d", $h, $m);
return $retval;
}
clockalize("17.5"); // 17:30
I am not sure if this is the best way to do this, but
$variabletocutcomputation = 60 * ($dec - $hour);
$min = round($variabletocutcomputation);
$sec = round((60*($variabletocutcomputation - $min)));
This is a great way and avoids problems with floating point precision:
function convertTime($h) {
return [floor($h), (floor($h * 60) % 60), floor($h * 3600) % 60];
}

Converting MP3 duration time

I'm using my iTunes library to get data from about 1,100 mp3s and I'm running into a small issue in getting the duration of the library into minutes and seconds.
$duration = 1893642;
$minutes = bcmod(($duration / 60), 60);
$seconds = bcmod($duration, 60);
echo $minutes.":".$seconds; //returns 0:42
The problem is that this specific MP3 is actually 31:42. Any thoughts on why this isn't working?
$minutes = bcmod(($duration / 60), 60);
is taking the minutes modulo 60. Unless your track is over an hour it will always say 0.
You want it to be
$minutes = floor($duration / 60);
Try this function
function formatTime($secs) {
$times = array(3600, 60, 1);
$time = '';
$tmp = '';
for($i = 0; $i < 3; $i++) {
$tmp = floor($secs / $times[$i]);
if($tmp < 1) {
$tmp = '00';
}
elseif($tmp < 10) {
$tmp = '0' . $tmp;
}
$time .= $tmp;
if($i < 2) {
$time .= ':';
}
$secs = $secs % $times[$i];
}
return $time;
}
Not sure if the following function was available when this question was written, but as it's a question I've been asking myself so here goes.
I used the answer above:
$seconds = bcmod($row{'playtime_seconds'}, 60);
$minutes = floor($row{'playtime_seconds'} / 60);
$hours = floor($minutes / 60);
Which works for the majority of times, but there is no padding - so you can end up with 20:1 when it should be 20:01 - and it's not to good over an hour - one length comes in at length="1:70:9" - so an alternative is to use the "date" function.
<?=date("H:i:s", $duration); ?>
which returns 00:31:42 from that number of seconds
$duration_str = sprintf('%s:%02s:%02s',
floor($duration_int / 3600), // hours
floor($duration_int / 60) - floor($duration_int / 3600) * 60, // minutes
$duration_int % 60); // seconds
The *printf functions provide formatting. In this case the leading zero.
The minutes line is the most complex part, since you have to calculate the hours (duration [s] / 3600 [s/h]), then round down to integer (floor()), then multiply with 60 to transform to minutes, then subtract that from the total number of minutes (duration [s] / 60 [s/m]).
If your durations are shorter than an hour, the code is much simpler:
$duration_str = sprintf('%s:%02s', floor($duration_int / 60), $duration_int % 60);
The result is still correct for a duration greater than 59 minutes, but just not as readable (31560 minutes in the example).

Categories