4

I am trying to create a random time for a notification to occur that is between two times, a range...

I would like iOS to create a time between say 09:30AM and 11:30AM.

I was thinking of using the random number generator for the hours and another one for the minutes and then do some checks to make sure it is between 09:30AM and 11:30 AM but thought there might be an easier way to do it with out getting too involved. any help would be greatly appreciated.

OscarTheGrouch
  • 2,374
  • 4
  • 28
  • 39
  • Does this time have to be an even number of minutes, or of seconds, or do you want it to be truly random, i.e. fractions of seconds? – matt Jan 21 '16 at 16:14

1 Answers1

8

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.

Tommy
  • 99,986
  • 12
  • 185
  • 204