1. use components:fromDate:toDate:options:
to determine the temporal difference between two dates in units other than seconds (which you could calculate with the NSDate
method timeIntervalSinceDate
NSDate *startDate = ...;
NSDate *endDate = ...;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
2. use the dateByAddingComponents:toDate:options:
method to add components of a date (such as hours or months) to an existing date
NSDate *today = [[NSDate alloc] init];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setHour:1];
[offsetComponents setMinutes:30];
// Calculate when, according to Tom Lehrer, World War III will end
NSDate *endOfWorldWar3 = [gregorian dateByAddingComponents:comps toDate:today options:0];
No comments:
Post a Comment