Tuesday, August 31, 2010

Creating Date from Epoch

I have worked with dates in ColdFusion for as long as I remember.  But recently I have realized that CF is very limited in allowing you to create dates from what are considered standard representations of dates in other programming languages.

So let us see...
I have now() which only gives me the current date/time.
I have createDate/createDateTime() which takes 3/6 arguments.

That's it!  Well what about Epoch AKA numeric date?  Come on Adobe, where is my createDate(milliseconds) function?

Well anyway, I could not live without a way to create dates from Epoch as I find this to be the best way of passing date/time objects between server and client and even other server-side languages.

Through some research I found where using the dateAdd() function to accomplish this, and the examples I found all used Epoch seconds which worked fine.  However, I wanted to use Epoch milliseconds which dateAdd() has a problem with.  The 2nd argument in dateAdd() takes an integer and milliseconds is a long which very quickly threw a nice CF error for me :)

So I figure since Java very easily allows us to create a date object this way, lets take advantage of that.

createObject('java', 'java.util.Date').init(javaCast('long', milliseconds));

And now, lets turn this into a simple reusable custom function.  Fortunately, the type="numeric" of <cfargument> does accept a long.

<cffunction returntype="date" name="createNumericDate" output="false">
<cfargument type="numeric" name="milliseconds" required="true" />
return createObject('java', 'java.util.Date').init(javaCast('long', arguments.milliseconds));

And there you have it.  The simplest way I could find to create a date in CF from Epoch milliseconds.