Convert Minutes and Hours to it's correspondant number - php

Sorry , I can't find good title for it.
I want to convert minutes and hours to a number.
Ex. :-
$hours = "3";
$minutes = "30";
It should show 3.5.
If I write 4 hours and 15 minutes then it shows 4.25.
I want to convert like this.

You need to just divide the minutes by there maximum value (60) and then add that to your hours to get the full value.
$hours = "3";
$minutes = "30";
echo $hours + ($minutes / 60);
Demo: https://eval.in/819401
Also note the + here is adding, not concatenating. If you concatenate you get an extra decimal place appended to the hours value because the decimal is 0.fractionvalue.

$convertedTime = (($hours * 60) + $minutes) / 60;
You will need to add some rounding or cutting off decimal digits

Related

converting milliseconds to amount of time string

So pretty much I'm storing the amount of play time a player has in milliseconds and I need to convert it to the amount of time it equals (string).
I've already tried it but I can't seem to get it to be accurate. I used rounding and it turned out poorly.
Can anybody help me out?
Example: 183547165 -> * days * hours * minutes * seconds
If I'm reading the question right, then I think you want something like this!
<?php
$milliseconds = '183547165';
$time = $milliseconds / 1000;
$days = floor($time / (24*60*60));
$hours = floor(($time - ($days*24*60*60)) / (60*60));
$minutes = floor(($time - ($days*24*60*60)-($hours*60*60)) / 60);
$seconds = ($time - ($days*24*60*60) - ($hours*60*60) - ($minutes*60)) % 60;
echo $days.' days<br>'.$hours.' hours<br>'.$minutes.' minutes<br>'.$seconds.' seconds';
?>
Converts milliseconds to days, hours, minutes, and seconds.
PHP has a date function which do what you want:
date("H:i:s", '183547165');
It outputs:
09:19:25
PHP DATE

How to convert minutes to hours and minutes (without days) [duplicate]

This question already has answers here:
Convert number of minutes into hours & minutes using PHP
(14 answers)
Closed 8 years ago.
I would like to display time in minues as an hour and minutes.
Example 1: I want to display 125 minutes as a 2:05
I know I can to somethink like:
$minutes=125;
$converted_time = date('H:i', mktime(0,$minutes);
This works fine, but if the time is more then 24h it is a problem.
Example 2:
$minutes=1510;
and I want to receive 25:10 (without days), only hours and minutes.
How to do that?
You can use:
$minutes=1510;
$hours = intdiv($minutes, 60).':'. ($minutes % 60);
!!! This only works with php >= v7.xx
Previous answer:
$minutes=1510;
$hours = floor($minutes / 60).':'.($minutes - floor($minutes / 60) * 60);
As simple as that.
$minutes = 125;
$hours = floor($minutes / 60);
$min = $minutes - ($hours * 60);
echo $hours.":".$min;
EDIT: should use floor() instead of round() for getting correct results.
$hours = floor($minutes / 60); // Get the number of whole hours
$minutes = $minutes % 60; // Get the remainder of the hours
printf ("%d:%02d", $hours, $minutes); // Format it as hours:minutes where minutes is 2 digits

Formating integers in percentage in php

I have two integers that are $hours = 74 and $minutes = 20, the format I need to get them in is following: hours and minutes (without any spacing) in percentage of one hour. So in this case the final result should be 7433.
Just to make it more clear if the two numbers would be $hours = 74 and $minutes = 30, the final result should be 7450.
I have been trying to look for similar functions, but without any success.
Any help or guidance is much appreciated.
So really what you are looking for is $result = $hours . floor($minutes/60*100); ?
Or if you need the leading zeroes: $result = str_pad($hours,2,'0') . str_pad(floor($minutes/60*100),2,'0');
Save yourself the pain of coming up with code that handles cases where the value of $minutes >= 60 by using the DateTimeInterface objects. I admit, they may seem overkill in this situation, but they are very sturdy and reliable. Plus, if ever you'd want to add days, weeks, months, years or seconds to this code, the DateTimeInterface classes are already equipped for the job:
$now = new DateTime();
$comp = clone $now;
//2 identical datetime instances
//add hours + minutes to either one
$comp->add(
sprintf(
'PT%dH%dM',
$hours,
$minuts
)
);
//get difference in seconds
$diff = $comp->getTimeStamp() - $now->getTimeStamp();
//or echo, I used printf to limit the number of decimals to 2
printf(
'%.2f hours difference'
$diff/3600 //1 hour === 3600 seconds
);
Just browse the DateTime docs, and other classes/interfaces like DateInterval and others implementing the DateTimeInterface.
Just for completeness, here's how I'd set about doing this "manually"
$decimalT = $hours + floor($minutes/60) + ($minutes%60)/60
//add hours in case $minutes>= 60
//floor($minutes/60);
//get remainder minutes, converted to decimal hours
//($minutes%60)/60;
printf(
'%d hours + %d seconds == %.2f hours',
$hours,
$minutes,
$decimalT
);
Use this snippet of code:
$hours = 74;
$minutes = 20;
$totalMinutes = $hours * 60 + $minutes;
$percentage = floor(($totalMinutes * 100) / 60);
var_dump($percentage);

mysql convert decimal time to xx:xx format

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;

form value 00:00:00 into time value

I was wondering, if I record a time through a javascript function and say I leave it on for 2 mins 20 seconds:
00.02.20
now when I insert this into my database, where the field type is set as time, it doesn't record properly.
I think it comes from how I request the data:
$length = mysql_escape_string($_REQUEST['timeDrive']);
is there a way of converting this into a time that is going to output the exact value:
00.02.20
thanks for the help!
If you don't need to perform any mathematical functions on those fields (eg: sum, average, etc), and it's purely for display, then you can just store it as plain text in a CHAR(8) field.
Otherwise, you'll need to normalise it to some sort of unit. I'd suggest maybe as an integer of the total number of seconds (if that is accurate enough for you).
To convert to seconds:
$val = "00.02.20";
$parts = explode(".", $val); // ['00', '02', '20']
$totalSeconds = parts[0] * 3600 + parts[1] * 60 + parts[2]; // 140
And to convert it back:
$seconds = 140; // this would be read from the database, or something
printf("%02d.%02d.%02d",
$seconds / 3600,
($seconds / 60) % 60,
$seconds % 60
);
Nope, not just like this.
It would be possible, if you make it just more simple and you just count the number of seconds in javascript. In your Database you can save it as integer or something.
The other way is you save it just as string, but then you can't compare the times.
Well, I'd save it as an integer, and if you want to show the time to somebody, you would have to format it before, like this:
function formatTime($seconds) {
$hours = floor($seconds / 3600); //by nickf
$minutes = floor($seconds / 60) % 60;
$sec = $seconds % 60;
$retHr = (strlen($hours) == 1 ? "0" . $hours : $minutes);
$retMin = (strlen($minutes) == 1 ? "0" . $minutes : $minutes);
$retsec = (strlen($sec) == 1 ? "0" . $sec : $sec);
return $retHr . "." . $retMin . "." . $retsec;
}
//now you counted one hour, two minutes and three seconds, you call it like
echo formatTime(3723);
//... and it outputs "01.02.03"

Categories