iPhone: How to convert “yyyyMMddThhmmss” format string to NSDate?

我怕爱的太早我们不能终老 提交于 2019-12-01 11:54:57

do like this,

NSString *dateStr = @"20121124T103000";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd'T'hhmmss"];
NSDate *d = [dateFormat dateFromString:dateStr];
NSString *st = [dateFormat stringFromDate:d];   
NSLog(@"%@",st);

Your original code is quite close; instead of:

@"yyyyMMddThhmmss"

You should be using:

@"yyyyMMdd'T'hhmmss"

The only difference is the pair of single quotes around the 'T' in the string- you just need to let the app know that 'T' is a part of the formatting, not the actual date.

Try the following Code.

NSString *dateStr = @"20121124T103000";
    NSDateFormatter *dtF = [[NSDateFormatter alloc] init];
    [dtF setDateFormat:@"yyyyMMdd'T'hhmmss"];
    NSDate *d = [dtF dateFromString:dateStr];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMdd'T'hhmmss"];
    NSString *st = [dateFormat stringFromDate:d];   
NSLog(@"%@",st]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!