Skip to main content
Ben Nadel at cf.Objective() 2012 (Minneapolis, MN) with: Nathan DeJong
Ben Nadel at cf.Objective() 2012 (Minneapolis, MN) with: Nathan DeJong

Using Rand() To Generate Random Times In ColdFusion

By
Published in Comments (6)

I was on the way to the bathroom (the Tea has to go somewhere) when this popped into my head: Since dates in ColdFusion are represented as floating numbers and the decimal represents the time of day, you can use ColdFusion's Rand() function to generate random times. Think about it; since Rand() gets a value that is between 0 and 1, this can be thought of as between 12:00 AM one day and 12:00 AM the next (1 = 12:00 AM of the next day).

Here's a little test:

<cfloop
	index="intI"
	from="1"
	to="10"
	step="1">

	#TimeFormat( Rand(), "hh:mm TT" )#

</cfloop>

Running the above code, we get:

09:46 PM
07:10 AM
07:48 AM
07:54 AM
03:20 PM
03:44 AM
08:23 PM
04:07 AM
10:05 PM
01:46 PM

Well anyway, this is really not that useful, but you never know. You might come up against a situation where picking random times is critical?? Good to know that this can easily be done.

Want to use code from this post? Check out the license.

Reader Comments

29 Comments

Here's an example:
"Service on between" and then you specify 2 dates
"Service on between" 1/12/2003 and 04/01/2007.

First of all you need to compare each value to the values stored in the db. Then you need to compare that 1/12/2003 is in between the dates stored in the db; same thing for 04/01/2007; and then you need to do the same for all the dates between 1/12/2003 and 04/01/2007. If you do date comparison, it will take a long time to get results. I'm not even talking about if you have a lot of results and the date ranges are bigger. Now, if you convert the dates to decimal point numbers, you will be comparing the numbers and not the dates, which is much faster and more efficient.

15,902 Comments

Ahhh, I see what you are saying. But, do you mean you actually store the value in a DateTime field in the database? Or is a float/decimal field type?

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel