Skip to content

Instantly share code, notes, and snippets.

@indragiek
Last active December 19, 2015 17:39
Show Gist options
  • Save indragiek/5992951 to your computer and use it in GitHub Desktop.
Save indragiek/5992951 to your computer and use it in GitHub Desktop.
Compile date as NSDate
+ (NSDate *)compileDate
{
BOOL (^stringContainsQuestionMark)(NSString *) = ^BOOL (NSString *string) {
return [string rangeOfString:@"?"].location != NSNotFound;
};
NSMutableString *dateString = @(__DATE__).mutableCopy;
NSString *timeString = @(__TIME__);
if (stringContainsQuestionMark(dateString) || stringContainsQuestionMark(timeString)) {
return nil;
}
[dateString appendFormat:@" %@", timeString];
static NSDateFormatter *compileDateFormatter = nil;
static NSDate *sentinel = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
compileDateFormatter = [[NSDateFormatter alloc] init];
compileDateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
compileDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
compileDateFormatter.dateFormat = @"MMM d yyyy HH:mm:ss";
sentinel = [NSDate dateWithString:@"2013-01-01 12:00:00 +0000"];
});
NSDate *date = [compileDateFormatter dateFromString:dateString];
// Check to make sure that the date isn't something messed up that precedes
// the sentinel date set at the start of 2013.
return ([date compare:sentinel] == NSOrderedAscending) ? nil : date;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment