iOS : Switching between 12/24 hour times from strings

Burf2000 picture Burf2000 · Aug 15, 2013 · Viewed 13k times · Source

Interesting issue thats caught me out.

I receive string times from a server to a device. which I then convert in to a NSDate. When the device was set to displaying 24hour times, life was good.

Now I am testing it on a device set to 12hour times. everything has stopped working. Dates are coming back as null

I first had

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"HH:mm"];
 self.startTime = [dateFormat dateFromString:(NSString *)self.startTime];

Worked perfectly for devices showing 24hour dates but not 12hour.

I then tried

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"hh:mm"];
 self.startTime = [dateFormat dateFromString:(NSString *)self.startTime];

This works fine up until 12 noon, then all dates are returned as null

Update

I have also tried adding "a" but this still results in returning null

 if (startDate == nil)
 {
      NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
      [dateFormat setDateFormat:@"hh:mm a"];
      startDate = [dateFormat dateFromString:(NSString *)self.startTime];
 }

Update 2

Adding local, adding :ss adding a all still do not work

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormat.locale = twelveHourLocale;
[dateFormat setDateFormat:@"hh:mm a"];
startDate = [dateFormat dateFromString:(NSString *)self.startTime];

Answer

Ian L picture Ian L · Aug 15, 2013

It's close... I think you need:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"HH:mm"];
startDate = [dateFormatter dateFromString:(NSString *)self.startTime];