Advanced Date Parsing with ColdFusion
By Pete Freitag
Have you ever tried to parse a date that ColdFusion didn't recognize? It can be pretty tricky, and usually requires regular expressions.
Suppose you want to use DateFormat
on an RFC-822 date. These dates are used by the HTTP protocol, and in RSS feeds. An RFC-822 date looks something like this: Wed, 31 May 2006 14:33:52 GMT
. You can pass this date into the ParseDateTime function, and it will return a date that you can format with DateFormat
, but it ignores the timezone. So if I were to pass a date like: Wed, 31 May 2006 10:33:52 EST
the ParseDateTime
function would not treat those two strings as the same date, even though they are equivalent.
Now you could parse out the timezone from the date string, but there is an easier way. Take a look at the SimpleDateFormat
java class. You simply initialize this object with a date pattern (see the javadocs for date mask characters), and call the parse
- it returns a java.util.Date
object (which is what ColdFusion dates are).
In this code example I am using the GetHttpTimeString
function to generate an RFC822 date string:
<cfset date = GetHttpTimeString()> <cfset formatter = CreateObject("java", "java.text.SimpleDateFormat")> <cfset formatter.init("EEE, dd MMM yyyy HH:mm:ss Z")> <cfset parsePosition = CreateObject("java", "java.text.ParsePosition")> <cfset parsePosition.init(0)> <cfset newDate = formatter.parse(date, parsePosition)> <cfoutput> GetHttpTimeString = #date# <br /> SimpleDateFormat = #newDate# <br /> ParseDateTime = #ParseDateTime(date)# </cfoutput>
When I run this code I get the following output:
GetHttpTimeString = Wed, 31 May 2006 14:33:52 GMT SimpleDateFormat = {ts '2006-05-31 10:33:52'} ParseDateTime = {ts '2006-05-31 14:33:52'}
Notice that the time is different in the result of the SimpleDateFormat
. This is because it has converted the date to my local timezone. Also notice that the result of ParseDateTime
has lost the timezone info.
Advanced Date Parsing with ColdFusion was first published on May 31, 2006.
The Fixinator Code Security Scanner for ColdFusion & CFML is an easy to use security tool that every CF developer can use. It can also easily integrate into CI for automatic scanning on every commit.
Try Fixinator
CFBreak
The weekly newsletter for the CFML Community
Comments
you don't need the ParsePosition bits, start w/DateFormat & do a getInstance (might want a DateTime instance). then you can do a simple parse(). you might also try just plain parse as i think it's inherited from DateFormat class.
as far as not knowing the date string format, you're out of luck if it's not one of the java standard ones (full-->short). which is why i *always* suggest using those instead of a custom mask. loop thru the standard styles in a cftry block tyrying to parse the date string. yeah i know, smashmouth programming but that's what most i18n java folks do.
Just adding more nit for the picking :)