我想要生成两个日期之间的随机日期--例如从今天到未来60天之间的一个随机日期。我该如何做到?
更新
根据答案提供的信息,我想出了这个方法,我经常使用:
// 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;
}