Last active
June 7, 2017 12:24
-
-
Save Abizern/2238027 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 hidden or 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 hidden or 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
Please convert it for Swift 3.x +