gpt4 book ai didi

ios - 计算从当前时间到指定时间的时间

转载 作者:行者123 更新时间:2023-11-30 13:23:04 25 4
gpt4 key购买 nike

我有一个UIDatePicker,它仅受时间限制。应用程序将从 datePicker 中选择的时间保存在变量中,当到达该时间时,它会触发 UILocalNotification

因此有一个标签显示本地通知触发之前的剩余时间。所以它的工作原理基本上有点像倒计时器。我怎样才能实现这个目标?

日期到字符串:(用于显示 fireDate)

func formatTimeForDisplay(date:NSDate) -> String {
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.timeStyle = NSDateFormatterStyle.ShortStyle
return formatter.stringFromDate(date)
}

NSLocalNotification 扩展:(用于将 NSDate 从 UIDatePicker 转换为 LocalNotification 的 fireDate)

extension NSDate {
var minute: Int {
return NSCalendar.currentCalendar().component(.Minute, fromDate: self)
}
var hour: Int {
return NSCalendar.currentCalendar().component(.Hour, fromDate: self)
}
var day: Int {
return NSCalendar.currentCalendar().component(.Day, fromDate: self)
}
var month: Int {
return NSCalendar.currentCalendar().component(.Month, fromDate: self)
}
var year: Int {
return NSCalendar.currentCalendar().component(.Year, fromDate: self)
}
var fireDate: NSDate {
let today = NSDate()
return NSCalendar.currentCalendar().dateWithEra(1,
year: today.year,
month: today.month,
day: { hour > today.hour || (hour == today.hour
&& minute > today.minute) ? today.day : today.day+1 }(),
hour: hour,
minute: minute,
second: 0,
nanosecond: 0
)!
}

最佳答案

为此,您需要使用 NSTimer 来更新倒计时标签。

在 ViewController 中,为计时器创建一个变量。

var timer = NSTimer()

我还设置了一个临时变量来保存 future 的日期 - 你没有发布代码,所以我不确定你的代码叫什么。在我的代码中,我将其称为 futureDate

let futureDate = NSDate().dateByAddingTimeInterval(60*60*2.4)

当您的用户选择一个日期并且您希望开始倒计时时,您将需要启动计时器来调用将更新标签的方法。在这个例子中,我称之为updateTimeLeft

timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "updateTimeLeft", userInfo: nil, repeats: true)

然后,我们只需计算当前和将来触发本地通知的日期之间的差异。我们在 updateTimeLeft 方法中执行此操作。在我的代码中,我有一个名为 timeLeftUILabelIBOutlet

func updateTimeLeft()
{
let elapsedTime = futureDate.timeIntervalSinceDate(NSDate())
self.timeLeft.text = NSDateComponentsFormatter().stringFromTimeInterval(elapsedTime)
}

关于ios - 计算从当前时间到指定时间的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37553110/

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