Add or Subtract days, months, year or time from or to a Date – iPhone SDK




Use NSCalendar to define the calendar system (we use the standard gregorian calender)

Use NSDateComponents to add or subtract components(days, months, year or time) from or to date.


NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *comps = [[NSDateComponents alloc] init];

[comps setMonth:-11];                    // here setting the Month component to -11, so I am subtracting 11 months from the current date

NSDate *toDate = [gregorian dateByAddingComponents:comps toDate: [NSDate date] options:0];
SocialTwist Tell-a-Friend
 

DateFormatting in iPhone SDK




.

.

Use NSDateFormatter class to playing around with dates.


NSDateFormatter *dtFrmt = [[NSDateFormatter alloc] init];

//use MM for 2 digit month, MMM for 3 char style and MMMM for full month name

[dtFrmt setDateFormat:@"MM/dd/yyyy"];              // like 01/31/2010

[dtFrmt setDateFormat:@"hh:mm:ss a"]                 // like 10:01:00 am

[dtFormat setDateFormat:@"EEEE hh:mm a"];    // like Sunday 11:11 pm
SocialTwist Tell-a-Friend