Dealing with military time (and some regular expression stuff too)
Had to convert military time into AM/PM. I thought there would be an easier way to do it, but couldn't find anything. Here's what I did:
First, I wrote a method to parse military time into an NSDateComponents object. Note that this uses a regular expression, which is a little tricky in iOS. Also, you could adjust the regex to parse AM/PM time into an NSDateComponents object.
- (NSDateComponents *) parseTimeStringIntoDateComponents: (NSString*) str {
NSDateComponents *dc = nil;
NSString *pattern = @"^([0-9]{2}):([0-9]{2})$";
NSRegularExpression *regex;
NSRange strRange = NSMakeRange(0, [str length]);
NSError *error = NULL;
regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive
error:&error];
if (error) {
LogError(@"Error parsing time into date components - %@", [error description]);
}
int numberOfMatches = [regex numberOfMatchesInString:str options:NSRegularExpressionCaseInsensitive range:strRange];
//NSLog(@"str: %@ matches:%d", str, numberOfMatches);
if (numberOfMatches > 0) {
NSTextCheckingResult *match = [regex firstMatchInString:str options:NSRegularExpressionCaseInsensitive range:strRange];
int hrs = [[str substringWithRange:[match rangeAtIndex:1]] intValue];
int min = [[str substringWithRange:[match rangeAtIndex:2]] intValue];
//NSLog(@"TimeString: %@ - hrs:%d, min:%d",str,hrs,min);
dc = [[NSDateComponents alloc] init];
[dc setHour:hrs];
[dc setMinute:min];
} else {
LogError(@"Time string is not formatted properly and cannot be parsed into date components");
}
return dc;
}
I also had to display the time in AM/PM format, so I wrote this method take the NSDateComponent and parse it into a string:
-(NSString*)convertTimeFromMilitary: (NSDateComponents*)dc{
// convert military time to AM/PM
int mHr = dc.hour;
int min = dc.minute;
int hr;
if(mHr == 0) {
hr = 12;
}else {
hr = mHr % 12;
}
return [NSString stringWithFormat:@"%d:%.2d %@", hr, min, (mHr >= 12 ? @"PM" : @"AM")];
}