我想在兩個日期之間生成一個隨機日期 - 例如今天到現在60天之間的隨機日期。我怎麼做?如何在objective-c中生成一個隨機日期?
UPDATE
運用的答案信息,我想出了這個方法,這是我經常使用:
// 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;
}
[最簡單的方法來在iPhone上的兩個NSDates之間循環?](http://stackoverflow.com/questions/3357257/simplest-way-to-loop-between-two-nsdates-on-iphone) – 2012-04-10 17:49:03
我不知道你在想什麼@luliusCæsar,但這個問題甚至沒有模糊地類似於兩個日期之間的循環... – memmons 2012-04-11 16:24:13
相同的代碼,重構和記錄https://gist.github.com/eirnym/c9526a045556e4d8464b41a367843e3c – 2016-04-26 13:39:39