从时间选择器值中减去分钟数?

Subtract minutes from time picker value?

这些天我一直在想如何从 Swift 中的时间选择器选择的时间中减去 3、10 和 20 分钟。例如,当用户选择事件的开始时间时,能够在从选择器时间值中选择前 3、10 或 20 分钟收到通知。我试过了

let value:TimeInterval = 1187.5 let periodComponents = startTimePicker.date.addingTimeInterval(-value)

对于之前的 20 分钟, 但我得到的值晚了 2 小时(可能是控制台只向我显示 GTM 时间)。是否可以安排来自 "periodComponens" 的通知每周在特定日期的选定时间重复?或者我应该使用其他减法?

使用内置 Calendar class:

let threeMinutesEarlier = Calendar.current.date(byAdding: .minute, value: -3, to: myPicker.date)

你的代码没有问题。 xcode 控制台默认只打印出 GMT 日期时间。如果你使用NSDateFormatter将你的NSDate转换成NSString并打印出来,结果将如你所料

如果您使用 UILocalNotification 并希望安排它每周触发,您可以将其提供的 属性 repeatInterval 设置为 NSCalendarUnitWeekOfYear

例如:

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDate *fireTime; // Your desired date time.

localNotif.fireDate = fireTime;
localNotif.repeatInterval = NSCalendarUnitWeekOfYear;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];