微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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;
}

解决方法

>生成1到60之间的随机
int r = arc4random_uniform(60) + 1;

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

>获取当前日期

[NSDate date];

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

原文地址:https://www.jb51.cc/c/115676.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐