简体   繁体   中英

Random Time in between two times (a range) iOS SDK

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM