iphone - 如何合并来自两个 UIDatePickers 的日期和时间?

标签 iphone ios uidatepicker

我的应用程序中有两个 UIDatePickers,一种模式用于选择日期,另一种模式用于时间模式。当到达确切的日期和时间时,我已发出通知。我能够在正确的时间触发提醒,但问题是没有检查日期。有什么办法可以同时查看日期和时间吗??

提前致谢...

编辑

NSDate *date1 = [datePicker date];
NSDate *date2 = [timePicker date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

unsigned unitFlagsDate = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponents *dateComponents = [gregorian components:unitFlagsDate fromDate:date1];
unsigned unitFlagsTime = NSHourCalendarUnit | NSMinuteCalendarUnit ;
NSDateComponents *timeComponents = [gregorian components:unitFlagsTime fromDate:date2];

[dateComponents setHour:[timeComponents hour]];
[dateComponents setMinute:[timeComponents minute]];

NSDate *combDate = [gregorian dateFromComponents:dateComponents];   

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil) return;
NSDate *fireTime = combDate;
localNotif.fireDate = fireTime;
localNotif.alertBody = @"Alert!";
localNotif.soundName = UILocalNotificationDefaultSoundName;  
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

最佳答案

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);

关于iphone - 如何合并来自两个 UIDatePickers 的日期和时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14597500/

相关文章:

ios - SWIFT - UIDatePicker - 开始和结束日期选择,但无法弄清楚如何将这两个日期调用到两个不同的文本框中

iphone - 在我自己的类中重写保留和释放方法

iphone - 在单独的文件中定义委托(delegate)函数(而不是在 ViewController 中)

ios - TableviewCells 未按预期插入

ios - 是否有开源的 Flurry 替代品?

ios - 每次调试测试后文档位置发生变化

objective-c - UIDatePicker 具有 15m 间隔但总是准确的时间作为返回值

swift - UIDatePicker 倒数计时器模式在 Xcode 10.3 中不会返回正确的时间

iphone - 如何在 iPhone 中寻找流式音频?

iphone - iOS 加速度计在后台(无限)