Dates can be a pain in the neck. Everything in programming generally follows some pretty straight forward rules and more often than not pure logic is involved…. that is of course until you comes across date and time functions. In a perfect world we would adopt the invention of metric time http://en.wikipedia.org/wiki/Metric_time – an elegant concept dividing a day into 100000 seconds and thus all calculations would be derived from there.

However as we need to deal with an ancient method for calculating date and time we inevitably run into issues daily in ‘developer world’. The issue in this case regards using the CF method of reading in a list of files from a directory and using the ‘datelastmodified’ date returned in the query. Unfortunately what should in all logic be a date object is in fact a string disguised as a a date…. it might look like a date, but it isn’t. This creates issues when trying to make calculations on the date say for instance to see how many files are older than 7 days. Using a normal CF function such as dateDiff will not work by throwing the date returned from cffile into it without first making it into a valid date object. Try the code below and you will see what i mean:

<cfdirectory action=”list” directory=”{place your directory path here}” name=”qDir”>

<cfloop query=”qDir”>
<cfoutput>
Date Last Modified: #qDir.datelastmodified# <br />
Is it a date?: #isDate(qDir.datelastmodified)# <br />
What CF thinks the data is: #day(qDir.datelastmodified)#/#month(qDir.datelastmodified)#/#year(qDir.datelastmodified)#<hr />
</cfoutput>
</cfloop>

The output will show the original cffile datelastmodified then using the day(), month(), year) functions of CF we reconstruct what CF really thinks that date is. As you will no doubt find it is a schamozzle where in some instances the day is the year, sometimes the month is the day and sometimes the year is the day, ie not very helpfull.

How do you fix this debacle i hear you ask? well.. you need to write a date parser that can make sense of what is being passed in and return a nice shiny date (or datetime) object not to dissimilar to the one below:

<cffunction name=”dateTimeFix”>
<cfargument name=”sDateTime” type=”string” required=”true”>
<cfset var sDate = listFirst(trim(arguments.sDateTime),” “)>
</cfset><cfset var sTime = listLast(trim(arguments.sDateTime),” “)>

</cfset><cfset var sDay = listGetAt(sDate,1,”/”)>
</cfset><cfset var sMonth = listGetAt(sDate,2,”/”)>
</cfset><cfset var sYear = listGetAt(sDate,3,”/”)>

</cfset><cfset var sHour = listGetAt(sTime,1,”:”)>
</cfset><cfset var sMin = listGetAt(sTime,2,”:”)>

<cfreturn createDateTime(sYear,sMonth,sDay,sHour,sMin,0)>
</cfreturn></cfset></cfargument></cffunction>

SOOOOooo date time users beware!!!

One Comment

  1. You’re so hot right now!


Post a Comment

*
*