Can I use NSDateFormatter to convert this date string to an NSDate?

I have this string...

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

and I'd like to extract the time portion from it (ie 16:00) and convert it to its 12-hour equivalent (ie 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!


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?


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"];

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

链接地址: http://www.djcxy.com/p/35174.html

上一篇: 日期格式化程序在NSDateFormatter

下一篇: 我可以使用NSDateFormatter将此日期字符串转换为NSDate吗?