2

I have this string...

2010-08-24T16:00:00-05:00

and I'd like to extract the time portion from it (i.e. 16:00) and convert it to its 12-hour equivalent (i.e. 04:00 pm). I'm trying to use NSDateFormatter to accomplish this, but it's not working...

NSDateFormatter* dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"hh:mm a"];
NSDate *date1 = [dateformatter dateFromString:[listOfTimes objectAtIndex:0]];
[dateformatter release];

Can I use NSDateFormatter with this date format? If not, how can I extract the time and convert it to its 12-hour time equivalent?

Thanks!

beeeefy
  • 527
  • 4
  • 10

3 Answers3

2

The problem has to do with parsing the colon. I asked the same question and the solution is here: How to parse a date string into an NSDate object in iOS?

Community
  • 1
  • 1
JohnRock
  • 6,795
  • 15
  • 52
  • 61
1

I think you should be able to do something like the following.


    // create the date formatter object 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    NSDate* date = [formatter dateFromString:dateString];
    // set up the new date format
    [formatter setDateFormat:@"hh:mm:ss"];
    NSString *twelveHourTime = [formatter stringFromDate:date];
    [formatter release];

Update: Fixed the dateFormatter string format. I had the line below, but the Z seems to be unnecessary. Timezones always screw me up. :-/

    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
Jerry Jones
  • 5,393
  • 2
  • 22
  • 14
  • hmmm...that didn't work, but it looks good to me. the date returned from [formatter dateFromString:dateString] returns an invalid string. – beeeefy Aug 24 '10 at 22:02
  • thanks, Jerry, but still no. I get back an . out of curiosity, have you tested this and it works? i'm wondering if i'm doing something wrong somewhere else. – beeeefy Aug 24 '10 at 23:02
  • Hmm, I'm sorry, I seem to be having a hard time transposing code today. I tested SOMETHING that worked, it was definitely not this. – Jerry Jones Aug 24 '10 at 23:50
  • The problem I'm having is that I can't find a way to support the colon in the timezone offset. – Jerry Jones Aug 25 '10 at 17:23
0

This answer needs to be updated. As of iOS 10 the system provided NSISO8601DateFormatter is available for this particular format.

BergQuester
  • 6,167
  • 27
  • 39