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

走远了吗. 提交于 2019-12-06 13:16:48
JohnRock

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!