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;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson