Get an NSTimeInterval
for the period between the two dates; get a single random number in that range; get a new date by offset from the first.
/*! Returns a random date in the range [start, end)
@param start The lower bound for random dates; returned dates will be equal to
or after the start date.
@param end The upper bound for random dates; dates will be before the end date.
@returns A random date.
*/
- (NSDate *)randomDateBetweenStart:(NSDate *)start end:(NSDate *)end
{
NSTimeInterval window = [end timeIntervalSinceDate:start];
NSTimeInterval randomOffset = drand48() * window;
return [start dateByAddingTimeInterval:randomOffset];
}
Addendum, a year-and-a-half later: an edit has pointed out that drand48
both has a well-defined sequence (including first value from program launch) and isn't a particularly advanced random number generator. I recommend srand48
or seed48
at program launch if the former is a problem, and something like ((double)arc4random() / UINT32_MAX)
in place of drand48
if you want to eliminate both problems — although that reduces the number of output values you can hit from 2^48 to 2^32, it should still get you sub-second decisions within any reasonable time interval.