NSDate with date component from one and time component from another NSDate

Cornelius picture Cornelius · Jun 24, 2012 · Viewed 22.1k times · Source

I have two UIDatePicker controls in my app, one configured with UIDatePickerModeDate and one with UIDatePickerModeTime.

I want to configure a NSDate object with the date from UIDatePicker one and the time from the second one ... how?

Thanks, Mark

Answer

melsam picture melsam · Jun 25, 2012

Assume date1 and date2 are your two NSDate values. date1 contains your date components and date2 contains your time components. Here's how you would combine them together:

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

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

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

// 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 = [gregorianCalendar dateFromComponents:components3];   

// combinedDate contains both your date and time!

For iOS 8.0 +

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

// Extract date components into components1
NSDateComponents *components1 = [gregorianCalendar components:(NSCalendarUnit)(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                                     fromDate:date1];

// Extract time components into components2
NSDateComponents *components2 = [gregorianCalendar components:(NSCalendarUnit)(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond)
                                                     fromDate:date2];

// 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 = [gregorianCalendar dateFromComponents:components3];

// combinedDate contains both your date and time!