将所选时间与当前时间进行比较 [英] compare selected time to current time
问题描述
我有一个 UIdatepicker 用来选择时间(不是日期).一旦选择了时间,我需要检查它是否是手机时钟中存储的当前时间,如果不是,则继续检查直到它是一个它执行此代码:
I have a UIdatepicker used to selected a time(not a date). Once the time is selected i need to check to see if it the current time stored in the phones clock, if it is not then keep check until it is one it is execute this code:
takephoto = true
示例:我在上午 10:29 打开应用程序,我选择 10:31 作为时间,在 10:31 take-hot = true
被执行.
Example: I open the app at at 10:29 am, i select 10:31 as a time, at 10:31 take-hot = true
is executed.
我查看了这个问题,但是它比较的是日期而不是时间.非常感谢任何帮助.
I looked at this question, however it compares the date not the time. Any help is much appreciated.
我也尝试过使用此代码,但它无法正常工作.我需要计时器准确(在实际时间的一秒内),此代码仅在一分钟内(实际时间)起作用:
I have also tried using this code but it does not work properly. I need the timer to be exact(within a second of the actual time), this code only works within a minute(of the actual time) :
var timercount = Timer()
viewdidload()
{
timercount = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(Check), userInfo: nil, repeats: true)
}
Func Check()
{
let nowdate = NSDate()(two date declare global Var)
let date2 = datePicker?.date
(chek the Time How Much Time Remain)
let elapsed = date2?.timeIntervalSince(nowdate as Date)
if Int(elapsed!) == 0
{
takePhoto = true
}
}
推荐答案
你通过 NSDate
把事情复杂化了.使用 Swift 的原生 Date
:
You are complicating things up by going NSDate
. Use Swift's native Date
:
func check() {
let fireDate = datePicker.date
if fireDate < Date() {
takePhoto = true
}
}
此外,您应该避免这种情况:
Also, you should avoid this:
if Int(elapsed!) == 0 { } // don't
原因是计时器可能会错过一个节拍(由于用户退出应用程序、系统太忙、四舍五入错误等)导致该条件未满足.始终检查现在是否已超过 fireDate
,如果是,请拍照.如果您只想拍摄一次照片,请添加另一个属性来表示,如下所示:
The reason is the timer may miss a beat (due to user quitting app, system too busy, rounding errors, etc.) that make that condition unmet. Always check if now is past the fireDate
and if true, take the photo. If you want to take the photo only once, add another property to indicate that, like so:
if fireDate < Date() && !photoTaken {
takePhoto = true
photoTaken = true
}
这篇关于将所选时间与当前时间进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!