Skip to content

Instantly share code, notes, and snippets.

@Abizern
Last active June 7, 2017 12:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Abizern/2238027 to your computer and use it in GitHub Desktop.
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.
//
// NSDate+RandomDate.h
//
//
#import <Foundation/Foundation.h>
@interface NSDate (RandomDate)
- (NSDate *)randomDateInYearOfDate;
@end
//
// 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
@hemangshah
Copy link

Please convert it for Swift 3.x +

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