How to combine date and time from two UIDatePickers?
Swift 5
version of the accepted answer if it might help.
/// Returns `Date` from date and time.
func combine(date: Date, time: Date) -> Date? {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.day, .month, .year], from: date)
let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: time)
var newComponents = DateComponents()
newComponents.timeZone = .current
newComponents.day = dateComponents.day
newComponents.month = dateComponents.month
newComponents.year = dateComponents.year
newComponents.hour = timeComponents.hour
newComponents.minute = timeComponents.minute
newComponents.second = timeComponents.second
return calendar.date(from: newComponents)
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:self.datePicker.date];
NSDateComponents *timeComponents = [calendar components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:self.timePicker.date];
NSDateComponents *newComponents = [[NSDateComponents alloc]init];
newComponents.timeZone = [NSTimeZone systemTimeZone];
[newComponents setDay:[dateComponents day]];
[newComponents setMonth:[dateComponents month]];
[newComponents setYear:[dateComponents year]];
[newComponents setHour:[timeComponents hour]];
[newComponents setMinute:[timeComponents minute]];
NSDate *combDate = [calendar dateFromComponents:newComponents];
NSLog(@" \ndate : %@ \ntime : %@\ncomDate : %@",self.datePicker.date,self.timePicker.date,combDate);
Try this:
Convert date into NSString and Time into NSString.
Apppend Time into date string.
Now convert that final string into NSDate
Example: (Add validations from ur side)
NSDate *date1 = [datePicker date];
NSDate *date2 = [timePicker date];
NSString *date = [NSString stringWithFormat:@"%@",date1];
NSString *time = [NSString stringWithFormat:@"%@",date2];
NSString *dateAndTime = [NSString stringWithFormat:@"%@ %@",date,time];
NSDate *dateTime = [self dateFromString:dateAndTime];
- (NSDate*) dateFromString:(NSString*)aStr
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
//[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss a"];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSLog(@"%@", aStr);
NSDate *aDate = [dateFormatter dateFromString:aStr];
[dateFormatter release];
return aDate;
}