我想获得当月的随机日期。
有没有简单的方法来获取月份的随机日期?
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];
希望这可以帮助 :)
斯威夫特版本:
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)