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];
}
Related
I want to get round values of system time.
For example consider, now time is 6:02PM and I want to get the output as 6:05PM.
Is there any method???
You can use the ceil function with php:
$next_five = ceil(time()/300)*300;
this will give you the next round five minutes
$now = time();
$next_five = ceil($now/300)*300;
This will round up even if one second above a five minute mark
User below function
function blockMinutesRound($hour, $minutes = '5', $format = "H:i") {
$seconds = strtotime($hour);
$rounded = round($seconds / ($minutes * 60)) * ($minutes * 60);
return date($format, $rounded);
}
//call
blockMinutesRound('20:11');// return 20:10
Hope it helps ;)
I wish to multiply 2 variables so that one of them is in the hour format (hh:mm),
How can I do so? The answer I am getting is 0:
<?php
$num = 5;
$timeUnit = "00:01";
$waitingTime = $num * $timeUnit;
echo $waitingTime;
I need to get 00:05 (5 min) in the output, but I am getting 0.
Hope this will help you
$num=100;
$timeUnit="00:02";
$timeUnit;
$time=explode(":",$timeUnit);
$waitingTime=$num*$time[1];
$minute = sprintf("%02d", ($waitingTime%60));
$hour = sprintf("%02d", ($waitingTime/60));
$current_time = floor($hour).':'.($minute);
echo $current_time;
$num=20;
$timeUnit="00:03";
$time=explode(":",$timeUnit);
$waitingTime=$num*$time[1];
$sec=$time[0]+$waitingTime%60;
$hour=floor($waitingTime/60);
$timeUnit1="".$hour.":".$sec."";
$current=strtotime($timeUnit1); //seconds of current time
echo date("H:i",$current);
You can do like this
I ended up converting the time into seconds, did the multiply and converted it to "time format" again:
$num=200;
$timeUnit="00:01:00";
$time=explode(":",$timeUnit);
$sec=$time[1]*60;
$sec=$sec*$num;
$diff = $sec;
$format = sprintf('%02d:%02d:%02d', ($diff / 3600), ($diff / 60 % 60), $diff % 60);
echo $format;
Thanks for your help
You can't compute string and digits this way.
All you would have to do would be to create a function/method that would implement the behavior you want and use it
I am trying to convert a decimal time into an actual time format with hours and minutes, ie: in xx:xx hours.
My query is:
select SUM(vt.vluchtdec) AS vluchttijddecimal
from tbl_vluchtgegevens vg
left join tbl_vluchttijd vt
on vg.vluchttijddec = vt.vluchttijdID
WHERE vg.vertrekdatum <=NOW();
And I am echoing
. $row['vluchttijddecimal'] .
I have also tried this, but this also still gives me my response in a decimal format:
$result = mysql_query("select SUM(vt.vluchtdec) AS vluchttijddecimal
from tbl_vluchtgegevens vg
left join tbl_vluchttijd vt
on vg.vluchttijddec = vt.vluchttijdID
WHERE vg.vertrekdatum <=NOW();");
while($row = mysql_fetch_array($result))
{
$dec = $row['vluchttijddecimal'];
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;
}
echo "" .$dec."";
In MS Access I would do something like this:
CInt([vluchttijddecimal]) & ":" & Format([vluchttijddecimal]*60 Mod 60;"00")
But this does not work or I don't know how to do so in MySQL / php.
For anyone that is interested... This is how you would convert decimal time (Where 0.1 == 6 minutes) to hours and minutes (0.2333 == 14 minutes) in MYSQL alone. no PHP is needed. This also accounts for the need to round seconds to minutes.
SELECT CONCAT(FLOOR(timeInDec),':', LPAD(ROUND((timeInDec - FLOOR(timeInDec)) * 60) % 60,2,0)) AS TimeInHoursMinutes
FROM YourTable;
Replace timeInDec with the column name that contains the decimal time you would like to convert.
This will return 0:06 for 0.1000 decimal value so leading zeros are accounted for in single digit minutes.
You can do this in you SQL statement something like this:
SELECT CONCAT(CEIL(mydecimal),':', LPAD(Floor(mydecimal*60 % 60),2,'0')) as formated text
Where mydecimal is your unformatted field name
I think I have calculated your time values... although it was kinda pain.
It appears your "decimal time" is "hours.minutes"? Rather horrible and definitely not a good format: for dealing with time its best to stick to integers that specify either a total of minutes/seconds/hours or whatever granularity you need.
But assuming it is hours.minutes, you should be able to do it like this in PHP:
while($row = mysql_fetch_array($result))
{
$dec = $row['vluchttijddecimal'];
return sprintf("%2d:%2d", floor($dec), floor(($dec - floor($dec))*100));
}
Hopefully I am correct in assuming that you mean, for example that 2.5 hours = 2H 30mins. If so, then your 'time' is a time interval and is best represented by the DateInterval class.
This function will do what you want:-
/**
* Converts a 'decimal time' in the format 1.5hours to DateInterval object
*
* #param Int $decimalTime
* #return DateInterval
*/
function decTimeToInterval($decimalTime)
{
$hours = floor($decimalTime);
$decimalTime -= $hours;
$minutes = floor($decimalTime * 60);
$decimalTime -= ($minutes/60);
$seconds = floor($decimalTime * 3600);
$interval = new \DateInterval("PT{$hours}H{$minutes}M{$seconds}S");
return $interval;
}
echo decTimeToInterval(512.168)->format("%H:%I:%S");
See it working
If you want to add times in the format 'H:i' without converting them to and from decimals, you can do it like this:-
function sumTimes($time1, $time2)
{
list($hours1, $minutes1) = explode(':', $time1);
list($hours2, $minutes2) = explode(':', $time2);
$totalHours = $hours1 + $hours2;
$totalMinutes = $minutes1 + $minutes2;
if($totalMinutes >= 60){
$hoursInMins = floor($totalMinutes/60);
$totalHours += $hoursInMins;
$totalMinutes -= ($hoursInMins * 60);
}
return "$totalHours:$totalMinutes";
}
echo sumTimes('12:54', '100:06') . PHP_EOL;
echo sumTimes('12:54', '100:20') . PHP_EOL;
See it working
This is what I used for my Payroll System:
SELECT If(total_late>0, LPAD(CONCAT(REPLACE(FLOOR(total_late/60) + FORMAT(total_late%60*0.01,2), '.', ':'), ':00'), 8, 0), '00:00:00') FROM MyTable
I multiplied it by 0.01 because my variables are in Seconds. Eg. 60.00 = 1min
I would suggest this to include seconds. It is based on #Richard's solutions. Just notice I've changed CEIL by FLOOR in #Richard's solution.
SET #timeInDec=1.505;
SELECT CONCAT(FLOOR(#timeInDec),':', LPAD(FLOOR(#timeInDec*60 % 60),2,'0'),':', LPAD(FLOOR(MOD(#timeInDec*60 % 60,1)*100),2,0)) as timeInDec;
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.
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).