Monday, February 1, 2010

Iphone NSDate and NSDateComponents

 

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendars.html#//apple_ref/doc/uid/TP40003470-SW1

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