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

余生长醉 提交于 2019-12-01 11:33:51

问题


I have a string like "20121124T103000" and I want to convert this to NSDate.

I tried converting it with dateFormatter date format "yyyyMMddThhmmss" but it gives output as 2001-01-01 00:00:00 +0000 which is incorrect.

What is the way we can convert this string to NSDate?

Here is my code:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMddThhmmss"];
NSLog(@"%@",[dateFormat dateFromString:@"20121124T103000"]);

Any help is appreciated.


回答1:


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);



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/13538658/iphone-how-to-convert-yyyymmddthhmmss-format-string-to-nsdate

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