字符串值未转换为日期格式

字符串值未转换为日期格式。 看下面的代码……

{ NSString * TempDate = [NSString stringWithFormat:@"%@ %@ %@",Datelbl.text,yearString,TimeLbl.text]; // result is Thursday, November 21 2013 3:05 PM NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat : [NSDateFormatter dateFormatFromTemplate:@"EEEE, MMMM d yyyy hh:mm a" options:0 locale:[NSLocale currentLocale]]]; AppointmentDate = [dateFormatter dateFromString:TempDate];// in .h file NSDate *AppointmentDate; } 

我的问题是appointmentDate显示零值? 为什么? 什么是我的错!

试试这种格式:

 [dateFormatter setDateFormat :@"EEEE',' MMMM d yyyy hh:mm a"]; 

您需要转义不属于格式(逗号)的字符。

我尝试过它现在有效:

 NSString *date = @"Thursday, November 21 2013 3:05 PM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat :@"EEEE',' MMMM d yyyy hh:mm a"]; NSDate *AppointmentDate = [dateFormatter dateFromString:date]; 

如果您的语言环境不是英语,请添加以下内容:

 NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; [dateFormatter setLocale:usLocale]; 

只有这一个适合你:

 [dateFormatter setDateFormat : @"EEEE, MMMM d yyyy hh:mm a"]; 

应该形成NSDateFormatter

 "EEEE, MMMM dd yyyy hh:mm a" it must match to your date string.