简体   繁体   中英

count time from current time to specific time

I have a UIDatePicker which is restricted to time only. The app saves the selected time from the datePicker in a variable and when this time is reached it fires a UILocalNotification .

So there is a label which shows the remaining time until the Local Notification fires. So it basically works a bit like a countdown Timer. How can I achieve this?

Date to String: (for displaying the fireDate)

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

Extension for NSLocalNotification: (for converting the NSDate from UIDatePicker to fireDate for the LocalNotification)

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
            )!
    }

To display user friendly string you may refer to NSDateComponentsFormatter if your app is targeted for iOS 8 and higher.

Also, you may encounter one problem. UIDatePicker gives back a NSDate object, which encapsulates amount of seconds from Jan 1, 2001. Even if you see only time component in date picker. This means, you should pay attention to the date value of UIDatePicker and maybe "fix" it with NSCalendar API.

To do this, you'll need to use an NSTimer to get update the count down label.

In your ViewController, create a variable for the timer.

var timer = NSTimer()

I also set up a temp variable to hold the future date - you didn't post code, so I'm not sure what yours is called. In my code, I refer to it as futureDate

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

When your use selects a date and you want the countdown to begin, you'll want to initiate the timer firing to call a method that will update the label. In thie example, i call it updateTimeLeft .

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

Then, we simply need to calculate the difference between now and the future date when the local notification will fire. We do that in the updateTimeLeft method. In my code, I have an IBOutlet to the UILabel called timeLeft .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM