Solved

Convert calculated time into decimal value in PHP

Posted on 2009-07-16
29
1,026 Views
Last Modified: 2013-12-13
I have an application that has a start and end time, plus a calculated time (en elapsed time).

It currently displays:

Date              Started       Ended         Time
2009-04-22  10:45 AM    08:00 PM    09:15:00

This what we want:

Date              Started       Ended         Time
2009-04-22  10:45 AM    08:00 PM     9.25

Change 09:15:00 hours to 9.25 value

0
Comment
Question by:rayluvs
  • 8
  • 8
  • 8
  • +3
29 Comments
 
LVL 14

Expert Comment

by:profya
ID: 24870248
function timetofloat($time)
{
list($h, $m)=split(":", $time);
return $h."." .(intval($m)*1.7);
}
0
 
LVL 14

Expert Comment

by:profya
ID: 24870274
This is better:
function timetofloat($time)
{
list($h, $m)=split(":", $time);
return $h."." .floor((intval($m)*1.66));
}

Open in new window

0
 
LVL 15

Expert Comment

by:dirknibleck
ID: 24870276
You could do something like:

floatval(date("h", $yourdate)) + floatval(date("i", $yourdate))/60
0
ScreenConnect 6.0 Free Trial

Want empowering updates? You're in the right place! Discover new features in ScreenConnect 6.0, based on partner feedback, to keep you business operating smoothly and optimally (the way it should be). Explore all of the extras and enhancements for yourself!

 
LVL 10

Expert Comment

by:ollyatstithians
ID: 24870329
I would use unix timestamps to store your dates and times. This makes it very easy to add and subtract from them. When you need to display them, you can use the date() function to control the formatting.
strtotime() is an easy way to make a timestamp.

Olly.
<?php
 
// Make time values
$starttime = strtotime('2009-04-22 10:45 AM');
$endtime = strtotime('2009-04-22 08:00 PM');
$elapsed = $endtime - $starttime;
 
// Display values
echo '
  <p>Date '.date('Y-m-d', $starttime).'</p>
  <p>Start '.date('h:i:s A', $starttime).'</p>
  <p>End '.date('h:i:s A', $endtime).'</p>
  <p>Time '.date('G:i', $elapsed).'</p>';
 
?>

Open in new window

0
 
LVL 7

Expert Comment

by:ajkhalifa
ID: 24870646
Make this in the beginning of the page:
<?php
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$start = $time;
?>

and this in the end of the page or the process:
<?php
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$finish = $time;
$totaltime = ($finish - $start);
printf ("<br><div align='right'><b>This page took %f seconds to load.", $totaltime."</b></div>");
?>

have fun bro
0
 

Author Comment

by:rayluvs
ID: 24870937
Ok....tried all and none gave me the result. Maybe I'm doing something wrong.

I want to have the "Time" column to display the time elapsed in decimal, no minutes.  The purose is for calculating against moneys.  So I need to convert:

"09:15:00"   --- change to ---->    "9.25"  and this value is a result of   9 + (15/60)

Here's my line that prints the data (the elapsed time is already saved in MySql):

 //hold db data in variables
   $fa = $row['tdate'];
   $st = date('h:i A', strtotime('today ' . $row['start']));
   $fi = date('h:i A', strtotime('today ' . $row['finish']));
   $tt = $row['elapsed_time'];

 //display them
   echo "<tr>\n\r";
   echo "<td valign=top><font size=".$fsize.">$fa</font></td>\n\r";
   echo "<td valign=top><font size=".$fsize.">$st</font></td>\n\r";
   echo "<td valign=top><font size=".$fsize.">$fi</font></td>\n\r";
   echo "<td valign=top><font size=".$fsize.">$tt</font></td>\n\r";
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24870946

<?php // RAY_decimal_time.php
error_reporting(E_ALL);
 
/* FROM THE OP
It currently displays:
 
Date          Started     Ended       Time
2009-04-22    10:45 AM    08:00 PM    09:15:00
 
This what we want:
 
Date          Started     Ended        Time
2009-04-22    10:45 AM    08:00 PM     9.25
 
Change 09:15:00 hours to 9.25 value
*/
 
// MAN PAGES HERE:
// http://us2.php.net/manual/en/function.time.php
// http://us2.php.net/manual/en/function.date.php
// http://us2.php.net/manual/en/function.strtotime.php
 
// HOW TO CAPTURE THE TIME AS A UNIX TIME STAMP
$unix_timestamp = time();
 
 
 
// CAPTURE A SIMULATED START TIME AS A UNIX TIME STAMP
$starting_time = strtotime('2009-04-22    10:45 AM'); // SIMULATE A START TIME
 
// CAPTURE A SIMULATED ENDING TIME AS A UNIX TIME STAMP
$ending_time   = strtotime('2009-04-22    08:00 PM'); // SIMULATE AN END TIME
 
 
 
// COMPUTE THE ELAPSED TIME IN SECONDS
$elapsed_time  = $ending_time - $starting_time;
 
 
// COMPUTE THE ELAPSED TIME IN HOURS AND FRACTIONS TO TWO DECIMAL PLACES (3,600 SECONDS PER HOUR)
$decimal_time            = (float)$elapsed_time / 3600.0;
$printable_decimal_time  = (string)round($decimal_time,2);
 
// SHOW THE OUTPUT
var_dump($printable_decimal_time);

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24871020
I think this may be somewhat brittle:

"09:15:00"   --- change to ---->    "9.25"  and this value is a result of   9 + (15/60)

What if the date changed, etc.  You would be better off storing a DATETIME string or a UNIX timestamp for the start and end, and using those values in the computation.

The key to the answer here will be in using strtotime() and date() correctly, then computing the decimal elapsed time by using 3,600 seconds per hour.

best regards, ~Ray
<?php // RAY_temp_decimal_time.php
error_reporting(E_ALL);
 
// "09:15:00"   --- change to ---->    "9.25"  and this value is a result of   9 + (15/60)
 
// MAN PAGES HERE:
// http://us2.php.net/manual/en/function.time.php
// http://us2.php.net/manual/en/function.date.php
// http://us2.php.net/manual/en/function.strtotime.php
 
// SET THE ELAPSED TIME IN SECONDS
$day_start     = strtotime("today");
$elapsed_time  = strtotime("today 09:15:00") - $day_start;
 
 
// COMPUTE THE ELAPSED TIME IN HOURS AND FRACTIONS TO TWO DECIMAL PLACES (3,600 SECONDS PER HOUR)
$decimal_time            = (float)$elapsed_time / 3600.0;
$printable_decimal_time  = (string)round($decimal_time,2);
 
// SHOW THE OUTPUT
var_dump($printable_decimal_time);

Open in new window

0
 
LVL 7

Expert Comment

by:ajkhalifa
ID: 24871045
I just changed last line... check if it works for u
<?php
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$start = $time;
?>

and this in the end of the page or the process:
<?php
$time = microtime();
$time = explode(" ", $time);
$time = $time[1] + $time[0];
$finish = $time;
$totaltime = ($finish - $start);
print date("H:i:s", mktime(0, 0, $totaltime, 0, 0, 0));
?>
0
 

Author Comment

by:rayluvs
ID: 24871261
I don't want to use the start / finish in the calculation.  The elapsed time is already considered in the SQL select ("sec_to_time(time_to_sec(finish)-time_to_sec(start)) as elapsed_time"); value is extracted from there.  The elapsed time is always of the same day, never starts on one day and finished the next.  

Can we convert just the elapsed time (elapsed_time from select)?  that is, any time elapsed 0:25:00 min,  1:30:00 hr/min, etc, to just to decimal value without considering the Start/End since its already donde in the SQL select?

0
 
LVL 14

Expert Comment

by:profya
ID: 24871356
Se how this works:
function timetofloat($time)
{
list($h, $m)=split(":", $time);
return $h."." .ceil ((intval($m)*1.66));
}

Time: 9:15
$h=9
m$=15
return "9"."25"
function timetofloat($time)
{
list($h, $m)=split(":", $time);
return $h."." .ceil ((intval($m)*1.66));
}

Open in new window

0
 
LVL 7

Expert Comment

by:ajkhalifa
ID: 24871362
oh, sorry, i hope i got your point...
use the mktime like this example...
lets say that today is 15th of july, 2009 the time is 10 pm... and i want to add 5 hrs so it wl be 3 am in the morning
i wl say:
print date("F j, Y, g:i a",mktime(22+5,0,0,07,15,2009));
0
 
LVL 14

Expert Comment

by:profya
ID: 24871376
I made a mistake by using floor in stead of Ceil function. I hope this work good.
0
 
LVL 14

Expert Comment

by:profya
ID: 24871405
1.66 I used in the function equals 1/60*100
0
 

Author Comment

by:rayluvs
ID: 24871595
profya I used your function and placed just before my "?>" in the PHP apps, and it worked.

But testing it and doing manual calculation I think we need to place 3 decimal points, not only for more accurate calcs with monies but so it could be align evenly..

This is how its displayed with your function:

Date               Start           End             Time
2009-04-22    10:45 AM   08:00 PM   09.25
2009-06-29    01:20 PM   04:00 PM   02.67
2009-06-30    08:00 AM   05:00 PM   09.0
2009-06-30    11:30 AM   01:00 PM   01.50
2009-07-01    08:00 AM   09:00 AM   01.0  
2009-07-01    11:00 AM   12:30 PM   01.50

And this is how we need to have it.  Can it be display with this type of format: xx.xxx ?

Date               Start           End             Time
2009-04-22    10:45 AM   08:00 PM   09.250
2009-06-29    01:20 PM   04:00 PM   02.667
2009-06-30    08:00 AM   05:00 PM   09.000
2009-06-30    11:30 AM   01:00 PM   01.500
2009-07-01    08:00 AM   09:00 AM   01.000  
2009-07-01    11:00 AM   12:30 PM   01.500

0
 

Author Comment

by:rayluvs
ID: 24871662
Definately we need the 3 decimal places.  Another report displays the totals and if I use 2 decimal points, theres is a difference for the accountant.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24871861
To get 3 decimal places, you would change this:

$printable_decimal_time  = (string)round($decimal_time,2);

into this:

$printable_decimal_time  = (string)round($decimal_time,3);
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24871907
@Ramante: Just a note, when I post a code snippet here, unless I have explicitly said it is UNTESTED, it is a segment of code that I have, in fact, tested.  I have seen a lot of examples that were nearly correct in theory but had syntax errors, etc.  As a matter of professional policy I try to avoid something like that by testing my posts before they go up on EE.  So you can copy my code verbatim, install it on your hosting service, run it and see what the output looks like.  You can also tinker with the parameters to see how different arguments create different output.

Hope that helps, ~Ray
0
 
LVL 14

Expert Comment

by:profya
ID: 24872038

function Time2Float($time)
{
list($h, $m)=split(":", $time);
return $h."." .round((intval($m)*1.6666),3);
}

Open in new window

0
 

Author Comment

by:rayluvs
ID: 24872068
Point well taken Ray_Paseur.

I tried it and your snippet and doesn't display the decimal point.  This is what I copied over.
(when I use the vardump in your snipplet it show garbage on screen)

Here what i copied:

$starting_time = strtotime($row['start']);
$ending_time   = strtotime($row['finish']);
$elapsed_time  = $ending_time - $starting_time;
$decimal_time  = (float)$elapsed_time / 3600.0;
$printable_decimal_time  = (string)round($decimal_time,3)
0
 

Author Comment

by:rayluvs
ID: 24872129
profya, your return the following:

2009-06-29   01:20 PM   04:00 PM   02.66.664

???
0
 

Author Comment

by:rayluvs
ID: 24872134
I'm playing woth of them to see whats I doing wrong
0
 
LVL 14

Expert Comment

by:profya
ID: 24872182
I hope this be useful:
function Time2Float($time)
{
list($h, $m)=split(":", $time);
return $h."." .round(floatval((intval($m)*1.6666)),3);
}

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24872197
Here is the object lesson in why I test my scripts before I post.  This function gives an answer that is close, but not quite right.  In addition, it does not dependably return three decimal places.  To do that, you need to convert the number to a string with the number_format() function.
<?php // RAY_inaccurate_decimal_time.php
error_reporting(E_ALL);
 
 
// FROM ANOTHER POST IN THIS THREAD
function Time2Float($time)
{
   list($h, $m)=split(":", $time);
   return $h."." .round((intval($m)*1.6666),3);
}
 
 
echo "<br/> 00:00 "; echo Time2Float('00:00');
echo "<br/> 00:05 "; echo Time2Float('00:05');
echo "<br/> 00:10 "; echo Time2Float('00:10');
echo "<br/> 00:15 "; echo Time2Float('00:15');
echo "<br/> 00:20 "; echo Time2Float('00:20');
echo "<br/> 00:30 "; echo Time2Float('00:30');
echo "<br/> 00:45 "; echo Time2Float('00:45');
echo "<br/> 00:60 "; echo Time2Float('00:60');
echo "<br/> 01:00 "; echo Time2Float('01:00');

Open in new window

0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 24872202
See if this makes sense.

best regards to all, ~Ray
<?php // RAY_temp_decimal_time.php
error_reporting(E_ALL);
 
// "09:15:00"   --- change to ---->    "9.25"  and this value is a result of   9 + (15/60)
 
// MAN PAGES HERE:
// http://us2.php.net/manual/en/function.time.php
// http://us2.php.net/manual/en/function.date.php
// http://us2.php.net/manual/en/function.strtotime.php
 
// SET THE ELAPSED TIME IN SECONDS
$day_start     = strtotime("today");
$elapsed_time  = strtotime("today 09:15:00") - $day_start;
 
 
// COMPUTE THE ELAPSED TIME IN HOURS AND FRACTIONS TO TWO DECIMAL PLACES (3,600 SECONDS PER HOUR)
$decimal_time            = (float)$elapsed_time / 3600.0;
 
// MAKE PRINTABLE TO THREE DECIMAL PLACES
$printable_decimal_time  = number_format(round($decimal_time,3), 3);
 
// SHOW THE OUTPUT
var_dump($printable_decimal_time);

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24872286
"(when I use the vardump in your snipplet it show garbage on screen)"

Then something did not get copied correctly, and I suggest that you post the code that produced the garbage so we can see what is wrong.  

If you want to post code here at EE, it is helpful to use the code snippet; that way we can all be looking at the same line numbers.  If you say something "does not work" or "prints garbage" - that is not really useful information.  We need to see the output, the error messages, etc., so we have some hope of understanding the situation and diagnosing the issues.
0
 

Author Comment

by:rayluvs
ID: 24872325
Ray_Paseur, I just doing your suggestion and passed it to the aacountant and it worked perfectly.

Thanx all
0
 
LVL 14

Expert Comment

by:profya
ID: 24872326
@Ray: You are right, the exception today is that I lost my computers hard drive and I am working using my experience to provide help as much as possible. If you monitored most of my solutions, you will discover that I do my best to provide the exact solution. I couldn't test this simple function today, that's why I say try this and I use logic to provide the solution I think it helps.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 24873261
@profya: You have my sympathies, and I hope you can recover the information from that hard drive.  I know what a pain it is to have something like that happen.  Please don't think I am picking on you - I very much value your posts here at EE.  I am just trying to make the point that, while we can be quick to accept an answer, sometimes it is better to wait a bit, test the suggestions and see what come out.

@Ramante: Thanks for the points.  It's a good question.

best regards to all, ~Ray
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question