-
-
Save dyegos/271ef898f3f2f73853499812c4995da7 to your computer and use it in GitHub Desktop.
Category on NSDate to return a random date in the same year as itself.
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
// | |
// NSDate+RandomDate.h | |
// | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSDate (RandomDate) | |
- (NSDate *)randomDateInYearOfDate; | |
@end |
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
// | |
// NSDate+RandomDate.m | |
// | |
// | |
#import "NSDate+RandomDate.h" | |
@implementation NSDate (RandomDate) | |
- (NSDate *)randomDateInYearOfDate { | |
NSCalendar *currentCalendar = [NSCalendar currentCalendar]; | |
NSDateComponents *comps = [currentCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:self]; | |
[comps setMonth:arc4random_uniform(12)]; | |
NSRange range = [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[currentCalendar dateFromComponents:comps]]; | |
[comps setDay:arc4random_uniform(range.length)]; | |
// Normalise the time portion | |
[comps setHour:0]; | |
[comps setMinute:0]; | |
[comps setSecond:0]; | |
[comps setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; | |
return [currentCalendar dateFromComponents:comps]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment