SpokaneDude
SpokaneDude

Reputation: 4974

NSDateFormatter not outputting what I expect

I have the following code that is supposed to format a time string ("0800") so I can then format it again into HH:MM format for display.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
if([timeString intValue] < 1000)
    dateFormatter.dateFormat = @"Hmm";
else
    dateFormatter.dateFormat = @"HHmm";

NSDate *date = [dateFormatter dateFromString:timeString];

If the time string length is less than 4 characters, then the format string is altered accordingly.

The problem is that if the time string is 0800, the dateFormatter returns nil from the conversion of timeString.

How can I fix this?

Upvotes: 0

Views: 41

Answers (1)

rmaddy
rmaddy

Reputation: 318774

You need to use HHmm regardless of the integer value of the time string. 0800 has the format HHmm, not Hmm. If the string were 800 then using Hmm would make sense.

Upvotes: 1

Related Questions