shimmoril
shimmoril

Reputation: 682

Average Time & Display In Specifc Format (Coldfusion)

Edit: Thanks to barnyr I have the average in seconds, so now I just need to convert it to the correct format. Unfortunately the Coldfusion functions noted by Peter only take a datetime object, so I'm back to being stumped by the conversion.

I have a two-fold question. I need to generate the average time it took Y users to complete a task, and then display the result in a specific format: x Years x Months x Weeks x Days x Hours x Minutes x Seconds.

My backend database is SQL Server 2008, and I'm running the queries through Coldfusion 10. Both columns are datetime fields.

The query is (similar to):

SELECT    Started_Date, Completed_Date
FROM      tbl_progress
WHERE     0=0

I then need to iterate through the query results, get the difference between the Completed_Date and Started_Date (ie. duration), average the results, and display as noted above.

From another thread on Stackoverflow I got the following code, but it will only work for the days/hours/minutes/seconds sections of the required format.

<cfloop query="complete_time">
    <cfset completed = ParseDateTime(complete_time.Completed_Date) />
    <cfset started = ParseDateTime(complete_time.Started_Date) />
    <cfset difference = (completed - started) /> 
    <cfset fixed_diff = Fix(difference) />  
    <cfset days = fixed_diff /> 
    <cfset hours = TimeFormat(difference, "H") /> 
    <cfset minutes = TimeFormat(difference, "m") />  
    <cfset seconds = TimeFormat(difference, "s")/ >
</cfloop>

I need to know how/where to do the averaging, and how to get the years/months/weeks values for my required format. Date math is definitely not my best subject! Thanks.

Upvotes: 1

Views: 452

Answers (2)

barnyr
barnyr

Reputation: 5678

I would do the work in the database if you possibly can:

SELECT    Started_Date, 
          Completed_Date, 
          DATEDIFF(Second, Started_Date, Completed_Date) AS sec_diff
FROM      tbl_progress

You can then compute the seconds into minutes, hours etc in ColdFusion.

As you work through the results, you could sum up the sec_diff values. Then divide them by the number of row in your result set.

You could also average the results in a query. Tave a look at SQL's AVG() function.

I'm not near a SQL server, but you may be able to use the following:

SELECT    Started_Date, 
          Completed_Date, 
          DATEDIFF(Second, Started_Date, Completed_Date) AS sec_diff,
          AVG(DATEDIFF(Second, Started_Date, Completed_Date)) AS average_task_time
FROM      tbl_progress

Upvotes: 3

Dan Bracuk
Dan Bracuk

Reputation: 20804

I suggest using the datediff function in sql server to get the number of seconds. Then in ColdFusion you don't use timeformat, you do math. Timeformat() takes a datetime object and returns a string.

Upvotes: 0

Related Questions