Created
August 29, 2014 14:00
-
-
Save maxehmookau/682f0daea4b9572ee1a7 to your computer and use it in GitHub Desktop.
Objective-C Categories for Converting NSNumber containing military time to NSDate
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
#import <Foundation/Foundation.h> | |
@interface NSNumber (SUBNumberAdditions) | |
- (NSDate *)sub_DateFromMilitaryTime; | |
- (BOOL)sub_isValidMilitaryTime; | |
@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
#import "NSNumber+SUBNumberAdditions.h" | |
@implementation NSNumber (SUBNumberAdditions) | |
- (NSDate *)sub_DateFromMilitaryTime { | |
if (![self sub_isValidMilitaryTime]) { | |
NSException *exp = [NSException exceptionWithName:@"SUBInvalidMilitaryTimeInput" | |
reason:@"The inputted military time cannot be above 2359 (11:59pm)" | |
userInfo:nil]; | |
@throw exp; | |
} | |
NSDateComponents *comps = [NSDateComponents new]; | |
[comps setMinute:[self intValue] % 100]; | |
[comps setHour:floor(self.intValue / 100)]; | |
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; | |
return [gregorian dateFromComponents:comps]; | |
} | |
- (BOOL)sub_isValidMilitaryTime { | |
BOOL valid = ([self intValue] > 2359) ? NO : YES; | |
return valid; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment