ios - Code is returning an incorrect number of days in calendar -
i making calendar practicing purposes , trying find number of days in particular month of particular year.
i successful in finding proper values until today, when not getting correct number of days february only. working fine earlier , made no changes of kind code.
my code:
-(nsdate *)startofmonth:(nsinteger)calendarmonth :(nsinteger)calendaryear { nsdate *date=[nsdate date]; nscalendar * calendar = [nscalendar currentcalendar]; nsdatecomponents * comps = [calendar components: nscalendarunityear | nscalendarunitmonth |nscalendarunitday fromdate:date]; [comps setmonth:calendarmonth]; [comps setyear:calendaryear]; nsdate * monthonlydate = [calendar datefromcomponents:comps]; nsdatecomponents * currentdatecomponents = [calendar components: nscalendarunityear | nscalendarunitmonth fromdate:monthonlydate ]; self.numberofdays = [[nscalendar currentcalendar] rangeofunit:nscalendarunitday inunit:nscalendarunitmonth fordate:monthonlydate].length ; nslog(@"number of days==%li",(long)self.numberofdays); nsdate * startofanymonth = [calendar datefromcomponents: currentdatecomponents]; nsdateformatter *weekday = [[nsdateformatter alloc] init]; [weekday setdateformat:@"eee"]; nsstring * currentday =[nsstring stringwithformat:@"%@",[weekday stringfromdate:startofanymonth]]; [self updatefirstdateofcurrentmonth:currentday]; return startofanymonth; }
i'm guessing reason working few days ago , isn't working today february february doesn't have 30th day (which today), , you're creating date object based on current day , changing month, without checking day.
but more that, logic isn't quite clear me - if you're going getting first day of specified month, why not create nsdate object based on components specified user, while providing 1 value day component? you're doing here creating date based on today, changing components , checking them values set manually (and therefore know).
also, if practicing purposes, mentioned, highly recommend providing names of parameters part of method declarations, otherwise calling less readable. in case, consider changing method name to:
- (nsdate *)startofmonth:(nsinteger)calendarmonth ofyear:(nsinteger)calendaryear
i hope helps. luck.
Comments
Post a Comment