89

My code is here:

func stringFromTimeInterval(interval:NSTimeInterval) -> NSString {

    var ti = NSInteger(interval)
    var ms = ti * 1000
    var seconds = ti % 60
    var minutes = (ti / 60) % 60
    var hours = (ti / 3600)

      return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds,ms)
}

in output the milliseconds give wrong result.Please give an idea how to find milliseconds correctly.

Lydia
  • 2,017
  • 2
  • 18
  • 34
  • Since NSTimeInterval doesn't normally handle milliseconds but seconds, my question is why the "*1000", and it should always be 0. If your implementations manage milliseconds, it should be "%1000" instead, no? – Larme Mar 05 '15 at 07:44
  • ya, you are correct it must %1000. I want accurate timing thats why i work with milliseconds. – Lydia Mar 05 '15 at 07:49
  • Of course NSTimeInterval handles fractions of a second (e.g. milliseconds). It's a floating point type, not an integer. – Matthias Bauch Mar 05 '15 at 07:56
  • @MatthiasBauch,@larme ya but my problem is when i find difference between two timings ex: 1:36:22 and 1:36:24 (hh:mm:ss format), it gives 00:00:01 instead of 00:00:02. Thats why i thought it may the variation in milliseconds. – Lydia Mar 05 '15 at 08:14
  • I want a solution for that problem also. – Lydia Mar 05 '15 at 08:14

15 Answers15

178

Swift supports remainder calculations on floating-point numbers, so we can use % 1.

var ms = Int((interval % 1) * 1000)

as in:

func stringFromTimeInterval(interval: TimeInterval) -> NSString {

  let ti = NSInteger(interval)

  let ms = Int((interval % 1) * 1000)

  let seconds = ti % 60
  let minutes = (ti / 60) % 60
  let hours = (ti / 3600)

  return NSString(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}

result:

stringFromTimeInterval(12345.67)                   "03:25:45.670"

Swift 4:

extension TimeInterval{

        func stringFromTimeInterval() -> String {

            let time = NSInteger(self)

            let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
            let seconds = time % 60
            let minutes = (time / 60) % 60
            let hours = (time / 3600)

            return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)

        }
    }

Use:

self.timeLabel.text = player.duration.stringFromTimeInterval()
Mohammad Razipour
  • 3,643
  • 3
  • 29
  • 49
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
  • 1
    Might need to add "% 24" for hours i.e. "let hours = (ti / 3600) % 24 – Gabriel Wamunyu Jul 17 '17 at 18:04
  • ms are wrong I've used ti*1000 instead otherwise I've always get 0 – Michał Ziobro May 30 '18 at 10:42
  • 2
    '%' is unavailable: For floating point numbers use truncatingRemainder instead – JBarros35 Nov 22 '19 at 12:02
  • This is locale-specific. Check out apple's unit docs here: https://developer.apple.com/videos/play/wwdc2020/10160/ This response also has side effects: this extension to `TimeInterval` applies to all `Double` values because `TimeInterval` is a typealias of `Double`. Here is the documentation declaration: `typealias TimeInterval = Double` – a1cd Aug 14 '21 at 14:21
38

SWIFT 3 Extension

I think this way is a easier to see where each piece comes from so you can more easily modify it to your needs

extension TimeInterval {
    private var milliseconds: Int {
        return Int((truncatingRemainder(dividingBy: 1)) * 1000)
    } 

    private var seconds: Int {
        return Int(self) % 60
    } 

    private var minutes: Int {
        return (Int(self) / 60 ) % 60
    } 

    private var hours: Int {
        return Int(self) / 3600
    } 

    var stringTime: String {
        if hours != 0 {
            return "\(hours)h \(minutes)m \(seconds)s"
        } else if minutes != 0 {
            return "\(minutes)m \(seconds)s"
        } else if milliseconds != 0 {
            return "\(seconds)s \(milliseconds)ms"
        } else {
            return "\(seconds)s"
        }
    }
}
Viktor Malyi
  • 2,298
  • 2
  • 23
  • 40
Jake Cronin
  • 1,002
  • 13
  • 15
  • 2
    Jake this could be a great answer, but the calculus are not 100% correct: | 3599 returns -1s | 12601 returns 3h -29m 1s – Kqtr Aug 05 '17 at 00:55
  • 4
    I've suggested an edit that fixes calculus. Thanks again for your answer! – Kqtr Aug 05 '17 at 01:11
  • @PaulS. No idea, it might have not been approved (yet?) – Kqtr Nov 02 '17 at 10:02
  • 1
    @PaulS. Turns out my edit suggestion has been rejected because it "deviates from the original intent of the post", but here is the link: https://stackoverflow.com/review/suggested-edits/16940597 – Kqtr Nov 02 '17 at 10:08
  • To avoid the calculus trouble, you may also count the remainder by yourself: interval = interval.rounded() let seconds = Int(interval) - (Int(interval / 60) * 60) – mirap Nov 19 '17 at 15:30
20

Swift 3 solution for iOS 8+, macOS 10.10+ if the zero-padding of the hours doesn't matter:

func stringFromTime(interval: TimeInterval) -> String {
    let ms = Int(interval.truncatingRemainder(dividingBy: 1) * 1000)
    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute, .second]
    return formatter.string(from: interval)! + ".\(ms)"
}

print(stringFromTime(interval: 12345.67)) // "3:25:45.670"
vadian
  • 274,689
  • 30
  • 353
  • 361
  • 1
    use formatter.zeroFormattingBehavior = .pad if you want to show zero – Sébastien REMY Nov 04 '17 at 14:34
  • @iLandes `.pad` does not add a leading zero for the most significant component (the hours in the answer). – vadian Nov 04 '17 at 14:44
  • @vadian It does for me iff `zeroFormattingBehavior = .pad` – idrougge Oct 15 '18 at 11:35
  • @idrougge Once again, not for the most significant component. In the example you won't get `"03:25:45.670"` not even with `.pad` – vadian Oct 15 '18 at 11:41
  • Aha, now I see what you mean. No, you won't get two-digit hours using `.pad`. – idrougge Oct 15 '18 at 12:01
  • Actually, it worked for me if I put the line to add `zeroFormattingBehaviour` to `.pad` before setting the `allowedUnits`. Like this. `formatter.zeroFormattingBehavior = .pad formatter.allowedUnits = [.hour, .minute, .second]` – Sanzv Jun 12 '23 at 16:43
19

Equivalent in Objective-C, based on the @matthias-bauch answer.

+ (NSString *)stringFromTimeInterval:(NSTimeInterval)timeInterval
{
    NSInteger interval = timeInterval;
    NSInteger ms = (fmod(timeInterval, 1) * 1000);
    long seconds = interval % 60;
    long minutes = (interval / 60) % 60;
    long hours = (interval / 3600);

    return [NSString stringWithFormat:@"%0.2ld:%0.2ld:%0.2ld,%0.3ld", hours, minutes, seconds, (long)ms];
}
14

Swift 4:

extension TimeInterval{

        func stringFromTimeInterval() -> String {

            let time = NSInteger(self)

            let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
            let seconds = time % 60
            let minutes = (time / 60) % 60
            let hours = (time / 3600)

            return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)

        }
    }

Use:

self.timeLabel.text = player.duration.stringFromTimeInterval()
Mohammad Razipour
  • 3,643
  • 3
  • 29
  • 49
12

I think most of those answers are outdated, you should always use DateComponentsFormatter if you want to display a string representing a time interval, because it will handle padding and localization for you.

lilpit
  • 337
  • 3
  • 9
  • 4
    That's true for 99% of cases. When `NSCalendar.Unit` which aren't supported by the `DateComponentsFormatter` are needed,( for example `.nanosecond`), then it get useful to use one of these methods. – valeCocoa May 20 '19 at 23:15
12

Swift 5. No ms and some conditional formatting (i.e. don't display hours if there are 0 hours).

extension TimeInterval{

func stringFromTimeInterval() -> String {

    let time = NSInteger(self)

    let seconds = time % 60
    let minutes = (time / 60) % 60
    let hours = (time / 3600)

    var formatString = ""
    if hours == 0 {
        if(minutes < 10) {
            formatString = "%2d:%0.2d"
        }else {
            formatString = "%0.2d:%0.2d"
        }
        return String(format: formatString,minutes,seconds)
    }else {
        formatString = "%2d:%0.2d:%0.2d"
        return String(format: formatString,hours,minutes,seconds)
    }
}
}
Clay Martin
  • 199
  • 1
  • 4
8

Swift 4, without using the .remainder (which returns wrong values):

func stringFromTimeInterval(interval: Double) -> NSString {

    let hours = (Int(interval) / 3600)
    let minutes = Int(interval / 60) - Int(hours * 60)
    let seconds = Int(interval) - (Int(interval / 60) * 60)

    return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds)
}
mirap
  • 1,266
  • 12
  • 23
4

swift 3 version of @hixField answer, now with days and handling previous dates:

extension TimeInterval {
    func timeIntervalAsString(_ format : String = "dd days, hh hours, mm minutes, ss seconds, sss ms") -> String {
        var asInt   = NSInteger(self)
        let ago = (asInt < 0)
        if (ago) {
            asInt = -asInt
        }
        let ms = Int(self.truncatingRemainder(dividingBy: 1) * (ago ? -1000 : 1000))
        let s = asInt % 60
        let m = (asInt / 60) % 60
        let h = ((asInt / 3600))%24
        let d = (asInt / 86400)

        var value = format
        value = value.replacingOccurrences(of: "hh", with: String(format: "%0.2d", h))
        value = value.replacingOccurrences(of: "mm",  with: String(format: "%0.2d", m))
        value = value.replacingOccurrences(of: "sss", with: String(format: "%0.3d", ms))
        value = value.replacingOccurrences(of: "ss",  with: String(format: "%0.2d", s))
        value = value.replacingOccurrences(of: "dd",  with: String(format: "%d", d))
        if (ago) {
            value += " ago"
        }
        return value
    }

}
Ohad Cohen
  • 5,756
  • 3
  • 39
  • 36
4

Swift 4 (with Range check ~ without Crashes)

import Foundation

extension TimeInterval {

var stringValue: String {
    guard self > 0 && self < Double.infinity else {
        return "unknown"
    }
    let time = NSInteger(self)

    let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
    let seconds = time % 60
    let minutes = (time / 60) % 60
    let hours = (time / 3600)

    return String(format: "%0.2d:%0.2d:%0.2d.%0.3d", hours, minutes, seconds, ms)

}
}
maslovsa
  • 1,589
  • 1
  • 14
  • 15
3

for convert hour and minutes to seconds in swift 2.0:

///RETORNA TOTAL DE SEGUNDOS DE HORA:MINUTOS
func horasMinutosToSeconds (HoraMinutos:String) -> Int {

    let formatar = NSDateFormatter()
    let calendar = NSCalendar.currentCalendar()
    formatar.locale = NSLocale.currentLocale()
    formatar.dateFormat = "HH:mm"

    let Inicio = formatar.dateFromString(HoraMinutos)
    let comp = calendar.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: Inicio!)

    let hora = comp.hour
    let minute = comp.minute

    let hours = hora*3600
    let minuts = minute*60

    let totseconds = hours+minuts

    return totseconds
}
Pablo Ruan
  • 1,681
  • 1
  • 17
  • 12
  • 2
    so complicate for a simple problem. – Sébastien REMY Jul 04 '16 at 06:12
  • It's worth mentioning that using DateFormatter is resource heavy and can be easily avoided. I wouldn't recommend using this approach though, it is a valid solution. – OhadM Nov 21 '19 at 08:52
  • I Downvoted because it's not formated, vars and lets in Portuguese or spanish, var in Pascal case and other issues. This is bad for my eyes – firetrap Dec 16 '19 at 20:07
3

Swift 4 Extension - with nanoseconds precision

import Foundation

extension TimeInterval {

    func toReadableString() -> String {

        // Nanoseconds
        let ns = Int((self.truncatingRemainder(dividingBy: 1)) * 1000000000) % 1000
        // Microseconds
        let us = Int((self.truncatingRemainder(dividingBy: 1)) * 1000000) % 1000
        // Milliseconds
        let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
        // Seconds
        let s = Int(self) % 60
        // Minutes
        let mn = (Int(self) / 60) % 60
        // Hours
        let hr = (Int(self) / 3600)

        var readableStr = ""
        if hr != 0 {
            readableStr += String(format: "%0.2dhr ", hr)
        }
        if mn != 0 {
            readableStr += String(format: "%0.2dmn ", mn)
        }
        if s != 0 {
            readableStr += String(format: "%0.2ds ", s)
        }
        if ms != 0 {
            readableStr += String(format: "%0.3dms ", ms)
        }
        if us != 0 {
            readableStr += String(format: "%0.3dus ", us)
        }
        if ns != 0 {
            readableStr += String(format: "%0.3dns", ns)
        }

        return readableStr
    }
}
Mick
  • 30,759
  • 16
  • 111
  • 130
3

You can use Measurement and UnitDuration to convert a TimeInterval value into any duration unit. To see milliseconds in the result you need UnitDuration.milliseconds that requires iOS 13.0, tvOS 13.0, watchOS 6.0 or macOS 10.15. I put all actions that should be done in func convertDurationUnitValueToOtherUnits(durationValue:durationUnit:smallestUnitDuration:) (Swift 5.1.3/Xcode 11.3.1):

import Foundation

@available(iOS 10.0, tvOS 10.0, watchOS 3.0, macOS 10.12, *)
func convert<MeasurementType: BinaryInteger>(
    measurementValue: Double, unitDuration: UnitDuration, smallestUnitDuration: UnitDuration
) -> (MeasurementType, Double) {
    let measurementSmallest = Measurement(
        value: measurementValue,
        unit: smallestUnitDuration
    )
    let measurementSmallestValue = MeasurementType(measurementSmallest.converted(to: unitDuration).value)
    let measurementCurrentUnit = Measurement(
        value: Double(measurementSmallestValue),
        unit: unitDuration
    )
    let currentUnitCount = measurementCurrentUnit.converted(to: smallestUnitDuration).value
    return (measurementSmallestValue, measurementValue - currentUnitCount)
}

@available(iOS 10.0, tvOS 10.0, watchOS 3.0, macOS 10.12, *)
func convertDurationUnitValueToOtherUnits<MeasurementType: BinaryInteger>(
    durationValue: Double,
    durationUnit: UnitDuration,
    smallestUnitDuration: UnitDuration
) -> [MeasurementType] {
    let basicDurationUnits: [UnitDuration] = [.hours, .minutes, .seconds]
    let additionalDurationUnits: [UnitDuration]
    if #available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) {
        additionalDurationUnits = [.milliseconds, .microseconds, .nanoseconds, .picoseconds]
    } else {
        additionalDurationUnits = []
    }
    let allDurationUnits = basicDurationUnits + additionalDurationUnits
    return sequence(
        first: (
            convert(
                measurementValue: Measurement(
                    value: durationValue,
                    unit: durationUnit
                ).converted(to: smallestUnitDuration).value,
                unitDuration: allDurationUnits[0],
                smallestUnitDuration: smallestUnitDuration
            ),
            0
        )
    ) {
        if allDurationUnits[$0.1] == smallestUnitDuration || allDurationUnits.count <= $0.1 + 1 {
            return nil
        } else {
            return (
                convert(
                    measurementValue: $0.0.1,
                    unitDuration: allDurationUnits[$0.1 + 1],
                    smallestUnitDuration: smallestUnitDuration
                ),
                $0.1 + 1
            )
        }
    }.compactMap { $0.0.0 }
}

This is how you can call it:

let intervalToConvert: TimeInterval = 12345.67
let result: [Int] = convertDurationUnitValueToOtherUnits(
    durationValue: intervalToConvert,
    durationUnit: .seconds,
    smallestUnitDuration: .milliseconds
)
print("\(result[0]) hours, \(result[1]) minutes, \(result[2]) seconds, \(result[3]) milliseconds") // 3 hours, 25 minutes, 45 seconds, 670 milliseconds

As you can see I did not use numeric constants like 60 and 1000 to get the result.

Roman Podymov
  • 4,168
  • 4
  • 30
  • 57
0

converted into an swift 2 extension + variable format :

extension NSTimeInterval {

    func timeIntervalAsString(format format : String = "hh:mm:ss:sss") -> String {
        let ms      = Int((self % 1) * 1000)
        let asInt   = NSInteger(self)
        let s = asInt % 60
        let m = (asInt / 60) % 60
        let h = (asInt / 3600)

        var value = format
        value = value.replace("hh",  replacement: String(format: "%0.2d", h))
        value = value.replace("mm",  replacement: String(format: "%0.2d", m))
        value = value.replace("sss", replacement: String(format: "%0.3d", ms))
        value = value.replace("ss",  replacement: String(format: "%0.2d", s))
        return value
    }

}

extension String {
    /**
     Replaces all occurances from string with replacement
     */
    public func replace(string:String, replacement:String) -> String {
        return self.stringByReplacingOccurrencesOfString(string, withString: replacement, options: NSStringCompareOptions.LiteralSearch, range: nil)
    }

}
HixField
  • 3,538
  • 1
  • 28
  • 54
-1

Here is slightly improved version of @maslovsa's, with Precision input param:

import Foundation

extension TimeInterval {

    enum Precision {
        case hours, minutes, seconds, milliseconds
    }

    func toString(precision: Precision) -> String? {
        guard self > 0 && self < Double.infinity else {
            assertionFailure("wrong value")
            return nil
        }

        let time = NSInteger(self)

        let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
        let seconds = time % 60
        let minutes = (time / 60) % 60
        let hours = (time / 3600)

        switch precision {
        case .hours:
            return String(format: "%0.2d", hours)
        case .minutes:
            return String(format: "%0.2d:%0.2d", hours, minutes)
        case .seconds:
            return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds)
        case .milliseconds:
            return String(format: "%0.2d:%0.2d:%0.2d.%0.3d", hours, minutes, seconds, ms)
        }
    }
}

and usage:

let time: TimeInterval = (60 * 60 * 8) + 60 * 24.18
let hours = time.toString(precision: .hours) // 08
let minutes = time.toString(precision: .minutes) // 08:24
let seconds = time.toString(precision: .seconds) // 08:24:10
let milliseconds = time.toString(precision: .milliseconds) // 08:24:10.799
Stanislau Baranouski
  • 1,425
  • 1
  • 18
  • 22