Created
April 26, 2016 13:38
-
-
Save eirnym/c9526a045556e4d8464b41a367843e3c to your computer and use it in GitHub Desktop.
Random Date generator for Objective C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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; | |
} |
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
Hey, I made a swift version here. https://gist.github.com/edmund-h/2638e87bdcc26e3ce9fffc0aede4bdad