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

时间:2013-11-21 10:06:54

标签: ios objective-c xcode cocoa-touch nsdate

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

    { 
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显示零值?为什么?什么是我的错误!!!

3 个答案:

答案 0 :(得分:2)

请尝试以下格式:

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

答案 1 :(得分:0)

只有这一个适合你:

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

答案 2 :(得分:0)

NSDateFormatter的形成应该是

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