开发者

NSString to NSDate for mm/dd/yyyy hh:mm:ss format

My date string that I am getting is 8/5/2011 1:38:13 PM of this format.开发者_如何学Go How do I convert it to NSDate?

I tried:

[dateFormatter setDateFormat:@"mm/dd/yyyy 'T' hh:mm:ss a"];
NSString *currentDate = [dateFormatter stringFromDate:currentDateString];

It returns nil. Any thoughts?


The reason it returns nil is because you are calling the wrong method, there is no T in your date string (characters inside of single quotes ' in are literals), and the PM is not "P.M.". Things that are not breaking it but are not completely correct is you are trying to parse the month as a minute and your date string can have a minimum of 1 digit month, day, and hour so you should not use 2 specifiers which would pad them if you were to create a string from the date. Try this:

NSString *currentDateString = @"8/5/2011 1:38:13 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
//Specify only 1 M for month, 1 d for day and 1 h for hour
[dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"]; 
NSDate *currentDate = [dateFormatter dateFromString:currentDateString];

NSLog(@"current date: %@", currentDate);
//Example of the format using the actual date
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);
[dateFormatter release];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜