CFLib.org – Common Function Library Project

CreateTimeStruct(timespan)

Last updated January 07, 2002

author

Dave Pomerance

Version: 1 | Requires: CF5 | Library: DateLib

Description:
User supplies timespan (a number) and a mask of d, h, m, or s (day, hour, minute, second respectively) to denote the time unit timespan is measured in. Timespan is required, mask defaults to s. The function returns a structure of days, hours, minutes, and seconds equivalent to supplied timespan.

Return Values:
Returns a structure.

Example:

<cfset timestruct = CreateTimeStruct(21403, "m")>

<cfoutput>
21403 minutes = #timestruct.d# days, #timestruct.h# hours, #timestruct.m# minutes, #timestruct.s# seconds
</cfoutput>

Parameters:

Name Description Required
timespan The timespan to convert. Yes

Full UDF Source:

/**
 * Converts a given number of days, hours, minutes, OR seconds to a struct of days, hours, minutes, AND seconds.
 * 
 * @param timespan      The timespan to convert. 
 * @return Returns a structure. 
 * @author Dave Pomerance (dpomerance@mos.org) 
 * @version 1, January 7, 2002 
 */
function CreateTimeStruct(timespan) {
    var timestruct = StructNew();
    var mask = "s";

    if (ArrayLen(Arguments) gte 2) mask = Arguments[2];

    // if timespan isn't an integer, convert mask towards s until timespan is an integer or mask is s
    while (Int(timespan) neq timespan AND mask neq "s") {
        if (mask eq "d") {
            timespan = timespan * 24;
            mask = "h";
        } else if (mask eq "h") {
            timespan = timespan * 60;
            mask = "m";
        } else if (mask eq "m") {
            timespan = timespan * 60;
            mask = "s";
        }
    }
    
    // only 4 allowed values for mask - if not one of those, return blank struct
    if (ListFind("d,h,m,s", mask)) {
        // compute seconds
        if (mask eq "s") {
            timestruct.s = (timespan mod 60) + (timespan - Int(timespan));
            timespan = int(timespan/60);
            mask = "m";
        } else timestruct.s = 0;
        // compute minutes
        if (mask eq "m") {
            timestruct.m = timespan mod 60;
            timespan = int(timespan/60);
            mask = "h";
        } else timestruct.m = 0;
        // compute hours, days
        if (mask eq "h") {
            timestruct.h = timespan mod 24;
            timestruct.d = int(timespan/24);
        } else {
            timestruct.h = 0;
            timestruct.d = timespan;
        }
    }
    
    return timestruct;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson