objective c - NSDateFormatter dateFromString returns null -


i want concatenate 2 nsdates via nsdatecomponents , [nsstring stringwithformat] [dtformatter datefromstring]. first 1 has complete format consisting of yyyy-mm-dd hh:mm:ss. second 1 has information hour , minute. want second date have other information first date excepting seconds (will added automatically?). think works until dtformatter formats string date. searched on stackoverflow no solution fix issue:

my code:

//pdate has complete date format nsdatecomponents *datecomponentscomplete = [[nscalendar currentcalendar] components:nsyearcalendarunit |nsdaycalendarunit | nsmonthcalendarunit fromdate:self.pdate]; //sunrise has incomplete format nsdatecomponents *datecomponentsincompletesunrise = [[nscalendar currentcalendar] components:nshourcalendarunit | nsminutecalendarunit fromdate:self.sunrise];  nsinteger day = [datecomponentscomplete day]; nsinteger month = [datecomponentscomplete month]; nsinteger year = [datecomponentscomplete year];  nsinteger hour = [datecomponentsincompletesunrise hour]; nsinteger minute = [datecomponentsincompletesunrise minute];  //concatenate   nsstring *strsunrise = [nsstring stringwithformat:@"%d-%d-%d %d:%d", year, month, day, hour, minute];  nslog(@"strsunrise %@ ",  strsunrise);  nsdateformatter* dtformatter = [[nsdateformatter alloc] init]; [dtformatter setformatterbehavior:nsdateformatterbehavior10_4]; [dtformatter settimezone:[nstimezone systemtimezone]]; [dtformatter setdateformat:@"yyyy-mm-dd hh:mm:ss"];  nsdate* dateoutput = [dtformatter datefromstring:strsunrise]; nslog(@"%@", [dateoutput class]); nslog(@"dateoutput %@ ", [dtformatter stringfromdate:dateoutput]); 

output:

strsunrise 2013-7-25 5:16  (null) dateoutput (null) 

your input string not match format:

format: @"yyyy-mm-dd hh:mm:ss" input:  @"2013-7-25 5:16"                         ^^^ missing :00 

you can fix small code mod:

nsstring *strsunrise = [nsstring stringwithformat:@"%d-%d-%d %d:%d:00", year, month, day, hour, minute];                                                                   ^^^ 

(or removing :ss format string).


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -