问题
String value not converting to date format. see my code below...
{
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;
}
My problem is appointmentDate displaying nil value?? why ? whats my mistake!!!
回答1:
Try this format:
[dateFormatter setDateFormat :@"EEEE',' MMMM d yyyy hh:mm a"];
You need to escape the character that is not part of the format (the comma).
I tried and it works now:
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];
If your locale is not english, add this:
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
回答2:
Only this one work for you:
[dateFormatter setDateFormat : @"EEEE, MMMM d yyyy hh:mm a"];
回答3:
formation of NSDateFormatter
should be
"EEEE, MMMM dd yyyy hh:mm a" it must match to your date string.
来源:https://stackoverflow.com/questions/20117861/string-value-not-converting-to-date-format