Skip to content

Instantly share code, notes, and snippets.

@maxehmookau
Created August 29, 2014 14:00
Show Gist options
  • Save maxehmookau/682f0daea4b9572ee1a7 to your computer and use it in GitHub Desktop.
Save maxehmookau/682f0daea4b9572ee1a7 to your computer and use it in GitHub Desktop.
Objective-C Categories for Converting NSNumber containing military time to NSDate
#import <Foundation/Foundation.h>
@interface NSNumber (SUBNumberAdditions)
- (NSDate *)sub_DateFromMilitaryTime;
- (BOOL)sub_isValidMilitaryTime;
@end
#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