rand_date_range.cfm.txt ( 9,202 Bytes )
This demonstrates how ColdFusion can create a random date between two given dates. This method functions similar to RandRange( intFrom, intTo ) and actually uses that method under the hood. If you abstract generating a random date between two given dates, it comes down to picking a random point in time. We can create this random point by adding a random time span to the "From Date", making sure, of course, that this random time span does not give us a date past the desired "To Date".
The beauty of time spans in ColdFusion is that they can be represented as a single floating point number. This puts us in the perfect position to use RandRange() to create random time spans. To make sure that we do not create too large a timespan, our bottom range parameter will be zero and our top range parameter will be the difference in seconds between the two out lier dates. Therefore, if we get a random second value and add it to the "From Date", we know we can never go past the "To Date."
Now to test it out. For the from and to dates, let's pick Now and one month from Now.
From: 2006-07-07
To: 2006-08-07
Now, get a random date between those to:
Random: 38931.4080093
As you can see above, the random date is in Time Span format (represented as a single floating point number). In order to fix that, all we have to do is run a date format on it. Now, keep in mind that ColdFusion still treats that as a valid date. You only need to change the formatting on it for display. You can add, diff, subtract all you want on the server side and its all good.
Formatted: 2006-08-02
Added July 7, 2006 / Updated July 7, 2006