Search code examples
iosswiftnsdatenstimernsdateformatter

Why does my timer starts at 4:00:00 ?


My Timer is starting at 4:00:00 while I want it to start at 0:00:00.

At the beginning I was using "mm:ss" as a dateFormatter, but it was problematic because as soon as my timer gets to 60 min, it restarts from 0.

I wanted my timer to keep going over 60min so I added "hh:mm:ss", but now my timer is starting at 4:00:00 instead of 0:00:00.

var timer = NSTimer()
var sec = 0

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTheTime"), userInfo: nil, repeats: true)
  }

func theTime(interval:NSTimeInterval) -> String {
    var dateFormatter = NSDateFormatter()
    var date = NSDate(timeIntervalSince1970: interval)
    dateFormatter.dateFormat = "h:mm:ss"
    return dateFormatter.stringFromDate(date)
  }

func updateTheTime(){
    sec++
    self.timeElapsed.text = self.theTime(Double(sec))
  }

Solution

  • You can remedy this by specifying the time zone for the formatter:

     dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    

    Frankly, though, I'd advise against manually counting seconds yourself, and instead save the start time and then use NSDateComponentsFormatter to format a nice counter:

    var timer: NSTimer?
    var startTime: NSDate!
    
    var formatter: NSDateComponentsFormatter = {
        let _formatter = NSDateComponentsFormatter()
        _formatter.allowedUnits = .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond
        _formatter.zeroFormattingBehavior = .Pad
        return _formatter
    }()
    
    func startTimer() {
        startTime = NSDate()
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "handleTimer:", userInfo: nil, repeats: true)
    }
    
    func stopTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    func handleTimer(timer: NSTimer) {
        timeElapsed.text = formatter.stringFromDate(startTime, toDate: NSDate())
    }