String value not converting to date format

孤人 提交于 2020-02-23 06:46:08

问题


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

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