Using Coldfusion to turn a string into a date

We have a customer that would like to upload a file, and this file is a delimited text file…

The first line is a Quoted date (“Tuesday, January 23, 2007”)… but as it gets read into coldfusion it is not a valid date… so what you have to do is convert it, using the “DateFormat()” function in coldfusion.

In the following example, I’ll go through the following steps.

1. Set a try/catch to handle unpredictable results

2. Getting the file from the current directory

3. Reading the file into CF as a variable

4. Creating a line break as a delimiter

5. Getting the first line of text

6. Stripping out the quotes

7. Converting the String into a date

8. Validating the date, and throwing a valid message

9. End the try/catch

CLICK HERE TO GET EXAMPLE TEXT FILE

CLICK HERE TO GET BAD EXAMPLE TEXT FILE

CLICK HERE TO SEE THE GOOD RESULTS

CLICK HERE TO SEE THE BAD RESULTS

1. Set a try/catch to handle unpredictable results

<!— create a try catch in case of the text file not having a valid date—>

<cftry>

2. Getting the file from the current directory

<!— set vars —>

<cfset msg = “”>

<cfset filePath = ExpandPath(“Example.txt”)>

3. Reading the file into CF as a variable

<!— read the file in as a variable —>

<cffile action=“read” file=“#filePath#” variable=“myFile”>

4. Creating a line break as a delimiter

<!— create the delimiter —>

<cfset line=chr(13)&chr(10)>

5. Getting the first line of text

<!— get the first line of the txt file —>

<cfset date = listGetAt(myFile,1,line)>

6. Stripping out the quotes

<!— get rid of the left and right characters… which are quotes(“) —>

<cfset date = replace(date,'”‘,“”,“All”)>

7. Converting the String into a date

<!— convert the string passed, into a date —>

<cfset date = DateFormat(date,“mm/dd/yyyy”)>

8. Validating the date

<!— set boolean to test off of, returns a true/false —>

<cfset validDate = isDate(date)>

9. End the try/catch

<!— catch the unpredictable errors —>

<cfcatch type=“any”>

<cfset msg = “CFCATCH :” & CFCATCH>

</cfcatch>

</cftry>

and now for the whole file all together, i even created a debug mode to show details… so all you would have to do is plug a ?debugmode=true into the URL, and it would show more info

<!— create a try catch in case of the text file not having a valid date—>

<cftry>

<!— set vars —>

<cfset msg = “”>

Page 1 of 2 | Next page