如何在objective-c中生成随机日期?

前端之家收集整理的这篇文章主要介绍了如何在objective-c中生成随机日期?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在两个日期之间生成一个随机日期,例如从今天到今天之间的随机日期.我怎么做?

UPDATE

使用答案中的信息,我想出了这种方法,我经常使用:

  1. // Generate a random date sometime between now and n days before day.
  2. // Also,generate a random time to go with the day while we are at it.
  3. - (NSDate *) generateRandomDateWithinDaysBeforeToday:(NSInteger)days
  4. {
  5. int r1 = arc4random_uniform(days);
  6. int r2 = arc4random_uniform(23);
  7. int r3 = arc4random_uniform(59);
  8.  
  9. NSDate *today = [NSDate new];
  10. NSCalendar *gregorian =
  11. [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  12.  
  13. NSDateComponents *offsetComponents = [NSDateComponents new];
  14. [offsetComponents setDay:(r1*-1)];
  15. [offsetComponents setHour:r2];
  16. [offsetComponents setMinute:r3];
  17.  
  18. NSDate *rndDate1 = [gregorian dateByAddingComponents:offsetComponents
  19. toDate:today options:0];
  20.  
  21. return rndDate1;
  22. }

解决方法

>生成1到60之间的随机
  1. int r = arc4random_uniform(60) + 1;
  2.  
  3. // Usage : arc4random_uniform(hi - lo + 1) + lo

>获取当前日期

  1. [NSDate date];

>使用NSDateComponents从你的天数组件中减去随机数,并生成一个新的日期.

猜你在找的C&C++相关文章