Advanced Date Parsing with ColdFusion
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.
Tweet
add to del.icio.us
| Tags: date, time, utc, gmt, rfc822, parsedatetime, simpledateformat, gethttptimestring, cfml
Trackbacks
Comments
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 :)
Post a Comment
Recent Entries
- Firefox Aurora now Supports Content Security Policy 1.0
- Writing Secure CFML cfObjective 2013 Slides
- Upgrading to Java 7 on Linux
- J2EE Sessions in CF10 Uses Secure Cookies
- Learn about ColdFusion Security at cfObjective 2013
- Session Loss and Session Fixation in ColdFusion
- FuseGuard 2.3 Released
- CKEditor Spell Checker Plugin





