How do you generate a random date in objective-c?

cocoa, cocoa-touch, ios, objective-c

Solution

Generate a random number between 1 and 60

int r = arc4random_uniform(60) + 1;

// Usage : arc4random_uniform(hi - lo + 1) + lo

Get current date

[NSDate date];

Use `NSDateComponents` to subtract the random number from your `days` component and generate a new date.

Problem

I'd like to generate a random date between two dates -- for example a random date between today and 60 days from now. How do I do that? UPDATE Using information from the answers, I came up with this method, which I use quite often: ``` // Generate a random date sometime between now and n days before day. // Also, generate a random time to go with the day while we are at it. - (NSDate *) generateRandomDateWithinDaysBeforeToday:(NSInteger)days { int r1 = arc4random_uniform(days); int r2 = arc4random_uniform(23); int r3 = arc4random_uniform(59); NSDate *today = [NSDate new]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *offsetComponents = [NSDateComponents new]; [offsetComponents setDay:(r1*-1)]; [offsetComponents setHour:r2]; [offsetComponents setMinute:r3]; NSDate *rndDate1 = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0]; return rndDate1; } ```

Original source

Related problems