Simon Baynes: Web Development

Handling Dates in ColdFusion

I just wanted to give some advice to those of you who are starting out with ColdFusion. Be very careful when using dates with ColdFusion, especially when inserting them into databases.

Say for example that you have used 3 select boxes to allow your user to input their date of birth. You will probably have variables resembling these:


Now some people try and amalgamate these into a date by concatenating them.

ie <cfset DOB = FORM.Date & "/" & FORM.Month & "/" & FORM.Year>

Now this is adequate for display purposes, but if you needed to upload it to a database it could go very wrong. You should assemble them into a ColdFusion date, using the CreateDate() function, after which you can display them any way you like.

<cfset DOB = CreateDate(FORM.Year, FORM.Month, FORM.Date)> 

This will create a ColdFusion date in the same format as is created with the Now() function. eg {ts '2004-12-22 00:00:00'}.

This variable can now be used to display dates in anyway you like using the DateFormat() function.

DateFormat(DOB, "DD/MM/YYYY")  

And now if you want to upload your date into a database you should use the CreateODBCDate() function.

By Simon Baynes