Tuesday, December 10, 2013

Date manipulation – Objective C

You can add/subtract days/months/years from an existing NSDate without much of complicated coding if you use NSCalendar and NSDateComponents. Following is an example how you can add a day to an existing NSDate. Notice that I have not bothered to check what the day is or the month or the year when arriving at the resulting date. Objective C handles those complications ☺

NSCalendar *calender = [NSCalendar currentCalendar];
//pass your NSDate object for fromDate
NSDateComponents *datecomp =[calender components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];

int day = datecomp.day;
[datecomp setDay:(day+1)];

NSDate *newdate = [calender dateFromComponents:datecomp];

No comments: