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"
Related
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
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);
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;
This should be easy...
I have a duration in seconds,
I want to output it in hours:minutes:seconds format
When I try...
// video duration is 1560 seconds
<?=date("h:i:s",$video->duration)?>
...it outputs 07:26:00 instead of 00:26:00. So I figure it's a time zone issue.
At the beginning of my application I set the timezone like this
date_default_timezone_set('America/Montreal');
Now I guess I would get my normal value if I change the timezone to GMT but I don't want to do that each time I want a simple duration (and re-set the timezone to America/Montreal)
What are my options?
date is used to get a human readable format for an unix timestamp, so it's not what you need. In other words that function is used to show a date (like 12.12.2012) and not the duration of your video
for that you can create a function that starts from the total number of seconds and does something like
$seconds = $total_time %60;
$minutes = (floor($total_time/60)) % 60;
$hours = floor($total_time/3600);
return $hours . ':' . $minutes . ':' . $seconds;
maybe you need to adjust this a bit, as I did not test it. also some tests to skip hours or minutes if the video is short
This is an old question but I thought I can provide an answer for this:
function convert_to_duration($total_time){
$seconds = $total_time %60;
$minutes = (floor($total_time/60)) % 60;
$hours = floor($total_time/3600);
if($hours == 0){
return $minutes . ':' . sprintf('%02d', $seconds);
}else{
return $hours . ':' . $minutes . ':' . sprintf('%02d', $seconds);
}
}
I need to find how much time is between to time values (their difference) which are over 24:00:00.
For example: how can I calculate the difference between 42:00:00 and 37:30:00?
Using strtotime, strptotime, etc is useless since they cannot go over 23:59:59 ....
$a_split = explode(":", "42:00:00");
$b_split = explode(":", "37:30:00");
$a_stamp = mktime($a_split[0], $a_split[1], $a_split[2]);
$b_stamp = mktime($b_split[0], $b_split[1], $b_split[2]);
if($a_stamp > $b_stamp)
{
$diff = $a_stamp - $b_stamp;
}else{
$diff = $b_stamp - $a_stamp;
}
echo "difference in time (seconds): " . $diff;
then use date() to convert seconds to HH:MM:SS if you want.
Date/Time variables and functions are not appropriate here as you're not storing time, but instead a time span of (I assume) hours, minutes, and seconds.
Likely your best solution is going to be to split each time span into their integer components, convert to a single unit (for instance, seconds), subtract them from each other, then re-build an output time span that fits with your application.
I havent tested this, but this might do what you want:
function timediff($time1, $time2) {
list($h,$m,$s) = explode(":",$time1);
$t1 = $h * 3600 + $m * 60 + $s;
list($h2,$m2,$s2) = explode(":",$time2);
$seconds = ($h2 * 3600 + $m2 * 60 + $s2) - $t1;
return sprintf("%02d:%02d:%02d",floor($seconds/3600),floor($seconds/60)%60,$seconds % 60);
}