I want to get a random date of the current month.
Is there any easy way to get the random date of the month?
I want to get a random date of the current month.
Is there any easy way to get the random date of the month?
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];
To generate random number, use
int r = arc4random() % days.length;
and then create a date
[dateComponents setDay:r];
NSDate *startDate = [calendar dateFromComponents:dateComponents];
Hope this helps :)
Swift version:
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)