Search code examples
iosswiftnsdatenstimernstimeinterval

Format NSTimeInterval with NSDate


I have a function in Swift that outputs the following information:

1970-01-01 00:00:06 +0000

1970-01-01 00:00:07 +0000

etc. It's essentially a stopwatch. I want to take that number and format it into just 00:00:00 with minutes, seconds and milliseconds. Here is the code I have:

func update() {
    currentTime = NSDate().timeIntervalSince1970
    elapsedTime = currentTime - startDateInterval
    var testDate = NSDate(timeIntervalSince1970: elapsedTime)
    println(testDate)

}

currentTime is a reference to the date every time that update() is pinged (every .01 seconds)

startDateInterval is a reference to the date that is stored when the stopwatch is started.

Any help would be greatly appreciated! :)


Solution

  • I guess what you are looking for is a

    var dateFormatter = NSDateFormatter()
    

    which you probably want to format like

        self.dateFormatter.dateFormat = "mm:ss:SSS"
        self.dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
    

    and for the output you need to insert a date-difference in there, i.e.

        let now = NSDate()
        let timeintervalTotal = now.timeIntervalSinceDate(self.startDateTotal)
        self.labelTotalTime.text = self.dateFormatter.stringFromDate(NSDate(timeIntervalSinceReferenceDate: timeintervalTotal))