2

我想获得当月的随机日期。

有没有简单的方法来获取月份的随机日期?

4

2 回答 2

14
NSDate *today = [NSDate date]; 
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:today];
NSRange days = [calendar rangeOfUnit:NSDayCalendarUnit 
                       inUnit:NSMonthCalendarUnit 
                      forDate:today];

要生成随机数,请使用

int r = arc4random() % days.length;

然后创建一个日期

[dateComponents setDay:r];
NSDate *startDate = [calendar dateFromComponents:dateComponents];

希望这可以帮助 :)

于 2012-07-09T04:42:10.933 回答
1

斯威夫特版本:

let date = Date()
let calendar = Calendar.current
var dateComponents = calendar.dateComponents([.year, .month, .day], from: date)
guard
    let days = calendar.range(of: .day, in: .month, for: date),
    let randomDay = days.randomElement()
else {
        return nil
}
dateComponents.setValue(randomDay, for: .day)
return calendar.date(from: dateComponents)
于 2021-01-18T06:21:21.937 回答