swift - 如何在 SwiftUI 中将 Date 转换为 DateComponents?
问题描述
我想在用户从 DatePicker 中选择时设置每日通知,但我不知道如何将选定的小时和分钟转换为 DateComponents 以匹配 UNCalendarNotificationTrigger。
这是我的日期选择器:
DatePicker("Choose time of notif", selection: $notifTime, displayedComponents: .hourAndMinute)
这是我的通知触发器:
var dateComponents = DateComponents()
dateComponents = notifTime
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
解决方案
您只需要使用 APIdateComponents
从date
属性中获取Calendar
,这需要重复。因此,在这种情况下,小时和分钟每天都在重复,因此您可以这样做:
var notifTime: Date
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: notifTime)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
推荐阅读
- python - 如何从音频信号中计算响度?
- bash - Bash 检查 file1 行是否部分包含在 file2 的行中
- c++ - std::vector 可以终止而不抛出
- dialogflow-es - Dialogflow:如何区分用户上下文
- c# - C# 多级字典.where 查找结果
- flutter - 如何在颤动中将列的子项与容器底部对齐
- java - JMeter 中的 Java 邮件 - 获取 java.lang.UnsupportedOperationException:尚未实现邮件功能的方法
- excel - 通过辅助地址发送电子邮件
- python - Python - 当我们有重复的键时,匹配相同的键并获取相应的值
- snowflake-cloud-data-platform - Snowflake 的 ODBC 问题