gpt4 book ai didi

ios - 你如何在 objective-c 中生成一个随机日期?

转载 作者:技术小花猫 更新时间:2023-10-29 10:41:32 26 4
gpt4 key购买 nike

我想在两个日期之间生成一个随机日期 - 例如,今天和从现在起 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;
}

最佳答案

获取一个随机数并将其用作时间间隔,然后将其添加到开始日期。例如

NSTimeInterval timeBetweenDates = [endDate timeIntervalSinceDate:startDate];
NSTimeInterval randomInterval = ((NSTimeInterval)arc4random() / ARC4RANDOM_MAX) * timeBetweenDates;

NSDate *randomDate = [startDate dateByAddingTimeInterval:randomInterval];

关于ios - 你如何在 objective-c 中生成一个随机日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10092468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com