Skip to content

Instantly share code, notes, and snippets.

@eirnym
Created April 26, 2016 13:38
Show Gist options
  • Save eirnym/c9526a045556e4d8464b41a367843e3c to your computer and use it in GitHub Desktop.
Save eirnym/c9526a045556e4d8464b41a367843e3c to your computer and use it in GitHub Desktop.
Random Date generator for Objective C.
/**
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.
@param days date range between today and minimum date to generate
@return random date
@see http://stackoverflow.com/questions/10092468/how-do-you-generate-a-random-date-in-objective-c
*/
- (NSDate *)generateRandomDateWithinDaysBeforeToday:(NSUInteger)daysBack {
NSUInteger day = arc4random_uniform((u_int32_t)daysBack); // explisit cast
NSUInteger hour = arc4random_uniform(23);
NSUInteger minute = arc4random_uniform(59);
NSDate *today = [NSDate new];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *offsetComponents = [NSDateComponents new];
[offsetComponents setDay:(day * -1)];
[offsetComponents setHour:hour];
[offsetComponents setMinute:minute];
NSDate *randomDate = [gregorian dateByAddingComponents:offsetComponents
toDate:today
options:0];
return randomDate;
}
@edmund-h
Copy link

@sumanc
Copy link

sumanc commented Nov 6, 2018

NSUInteger day = arc4random_uniform((u_int32_t)daysBack);  // explisit cast should be

NSUInteger day = arc4random_uniform((u_int32_t)daysBack) + 1;  // explisit cast

If you don't add 1, you will randomly get time in the future because arc4random_uniform generates numbers from 0 to max -1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment