compare selected time to current time

2019-09-15 02:42发布

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

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
      }

}

标签: swift time timer
1条回答
姐就是有狂的资本
2楼-- · 2019-09-15 03:08

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

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
}
查看更多
登录 后发表回答