CFLib.org – Common Function Library Project

splitDateSpanToDays(spanStart, spanEnd)

Last updated March 18, 2010

author

Rodion Bykov

Version: 0 | Requires: CF5 | Library: DateLib

Description:
Function splits date span into array of periods (smaller date spans), from first day to last day.

Return Values:
Returns an array.

Example:

<cfset spanStart = dateAdd("d", -2, Now()) />
<cfset spanEnd = dateAdd("h", -2, Now()) />
<cfset periods = splitDateSpanToDays(spanStart, spanEnd) />

<cfdump var="#spanStart#" />
<cfdump var="#spanEnd#" />
<cfdump var="#periods#" />

Parameters:

Name Description Required
spanStart Start date Yes
spanEnd End date Yes

Full UDF Source:

/**
 * Splits date span to array of days (periods)
 * 
 * @param spanStart      Start date (Required)
 * @param spanEnd      End date (Required)
 * @return Returns an array. 
 * @author Rodion Bykov (rodionbykov@gmail.com) 
 * @version 0, March 18, 2010 
 */
function splitDateSpanToDays(spanStart, spanEnd){

    var result = arrayNew(1);
    var period = structNew();
    var firstDayStart = now();
    var firstDay = arguments.spanStart;
    var firstDayEnd = createDateTime(year(firstDay), month(firstDay), day(firstDay), 23, 59, 59);
    var currentDay = now();
    var lastDayStart = now();
    var lastDay = arguments.spanEnd;
    var lastDayEnd = createDateTime(year(lastDay), month(lastDay), day(lastDay), 23, 59, 59);
    var daysBetween = 0;
    var i = 0;
    
    if (dayOfYear(firstDay) eq dayOfYear(lastDay)) {
        period = structNew();
        period.start = firstDay;
        period.end = lastDay;
        temp = arrayAppend(result, period);
    }else{
        firstDayStart = createDateTime(year(firstDay), month(firstDay), day(firstDay), 0, 0, 0);
        lastDayStart = createDateTime(year(lastDay), month(lastDay), day(lastDay), 0, 0, 0);
        daysBetween = dateDiff("d", firstDayStart, lastDayStart) - 1;
        
        period = structNew();
        period.start = firstDay;
        period.end = firstDayEnd;
        temp = arrayAppend(result, period);
        
        if (daysBetween gt 0) {
            for (i = 1; i lte daysBetween; i = i + 1) {
                period = structNew();
                currentDay = dateAdd("d", i, firstDayStart);
                period.start = currentDay;
                currentDay = dateAdd("d", i, firstDayEnd);
                period.end = currentDay;
                temp = arrayAppend(result, period);
            }
        }
        
        period = structNew();
        period.start = lastDayStart;
        period.end = lastDay;
        temp = arrayAppend(result, period);
        
    }
    
    return result;
}

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