gpt4 book ai didi

ios - 从字符串时间 4 :01 to 3:51 in swift 开始递减 int

转载 作者:行者123 更新时间:2023-11-28 10:36:22 25 4
gpt4 key购买 nike

您好,我想从字符串时间发出本地通知,我希望通知在给定时间前 10 分钟启动。我有麻烦如何把时间从 4:01 变成 3:51,请帮助。这是我的代码

let a = "4:01"

func startNoftification(prayer: String) {
let time = prayer.split(separator: ":").map { (x) -> Int in
return Int(String(x))!
}
let content = UNMutableNotificationContent()
content.title = "Adzan"
content.body = "it's time to sholat dzuhur"

let gregorian = Calendar(identifier: .gregorian)
var component = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
component.hour = time[0]
component.minute = time[1] - 10

guard let date = gregorian.date(from: component) else { return }
let triggerDaily = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: "Hijrah", content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request) { (error) in
if let err = error {
print("Notif error:", err)
return
}
}
}

最佳答案

这是你需要的吗?

let time = "4:01"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm"

guard let date = dateFormatter.date(from: time) else {
return
}

let targetTime = Date(timeInterval: -(10 * 60), since: date) // Change time interval to required value in seconds
let targetTimeString = dateFormatter.string(from: targetTime)
print(targetTimeString) // Prints 3:51

或者,如果您的倒计时时间有很多时间组件,请使用 DateComponents

var dateComponents = DateComponents()
dateComponents.minute = -10
// Other components

if let targetTime = Calendar.current.date(byAdding: dateComponents, to: date)
print(dateFormatter.string(from: targetTime))
}

关于ios - 从字符串时间 4 :01 to 3:51 in swift 开始递减 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53425898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com