Wednesday, 22 August 2012

Combine two NSDates | Add date component + time component = NSDate

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// Extract date components into components1
NSDateComponents *components1 = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:YOUR_FIRST_DATE];

// Extract time components into components2
NSDateComponents *components2 = [calendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit 
fromDate:YOUR_SECOND_DATE];

// Combine date and time into components3
NSDateComponents *components3 = [[NSDateComponents alloc] init];

[components3 setYear:components1.year];
[components3 setMonth:components1.month];
[components3 setDay:components1.day];    

[components3 setHour:components2.hour];
[components3 setMinute:components2.minute];
[components3 setSecond:components2.second];         

// Generate a new NSDate from components3.
NSDate *combinedDate = [calendar dateFromComponents:components3];   

// combinedDate contains both your date and time!
NSLog(@"%@", combinedDate);

No comments:

Post a Comment