Cocoa: Date and Time

Add seconds to date

// add one hour
[date dateByAddingTimeInterval: 60 * 60]

Custom date

NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2011];
[components setMonth:3];
[components setDay:12];
[components setHour:23];
[components setMinute:45];
 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
 
NSDate *date = [gregorian dateFromComponents:components];

Tomorrow or next day

- (NSDate *)nextDay:(NSDate *)date {
	NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
 
	NSDateComponents *comps = [[NSDateComponents alloc] init];
	[comps setDay:1];
	NSDate *newDate = [gregorian dateByAddingComponents:comps toDate:date options:0];
	[comps release];
 
	// optional: reset to midnight
	NSDateComponents *comps2 = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:newDate];
	newDate = [gregorian dateFromComponents:comps2];
 
	[gregorian release];
 
	return newDate;
}
 
- (NSDate *)tomorrow {
	NSDate *now = [NSDate date];
	NSDate *tomorrow = [self nextDay:now];
 
	return tomorrow;
}

Reference

Feedback