86

If I have an NSTimeInterval that is set to say 200.0, is there a way to convert that into 00:03:20, I was thinking I could initialise an NSDate with it and then use NSDateFormatter using HH:mm:ss. My question is, is there a quick way to do this or do I have to break up the number myself and use [NSString stringWithFormat: %02d:%02d:%02d, myHour, myMin, mySec]?

12 Answers 12

201

No need to use NSDateFormatter or anything else than division and modulo. NSTimeInterval is just a double containing seconds.

Swift

func stringFromTimeInterval(interval: NSTimeInterval) -> String {
    let interval = Int(interval)
    let seconds = interval % 60
    let minutes = (interval / 60) % 60
    let hours = (interval / 3600)
    return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}

Objective-C

- (NSString *)stringFromTimeInterval:(NSTimeInterval)interval {
    NSInteger ti = (NSInteger)interval;
    NSInteger seconds = ti % 60;
    NSInteger minutes = (ti / 60) % 60;
    NSInteger hours = (ti / 3600);
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", (long)hours, (long)minutes, (long)seconds];
}
9
  • Much appreciated, thats what I was thinking but I just wanted to check that I was not missing something already included as part of the iOS SDK.
    – fuzzygoat
    Commented Feb 8, 2011 at 13:11
  • 1
    I want to point out that ":" works as a delimiter only in English and some other languages. Finnish, for example, uses "." - like this "15.02.59"
    – sgosha
    Commented Aug 5, 2014 at 20:09
  • @sgosha, exactly, normally Apple tends to provide formatters for these. Should I instead use a localized string for formatting?
    – Gerry Shaw
    Commented Aug 21, 2014 at 16:23
  • 23
    this is the wrong answer since it doesn't localize the delimiter (as other comments mention). using NSDateCompomentsFormatter you can correctly format your time interval in a single line, e.g. NSDateComponentsFormatter().stringFromTimeInterval(NSTimeInterval(duration)) in swift Commented Jun 3, 2015 at 18:06
  • 4
    For localization and future proofing, the correct solution is to use NSDateComponentsFormatter as described by @jrc
    – voidref
    Commented Jul 2, 2015 at 0:52
106

On iOS 8, use NSDateComponentsFormatter.

NSDateComponentsFormatter *dateComponentsFormatter = [[NSDateComponentsFormatter alloc] init];
NSLog(@"%@", [dateComponentsFormatter stringFromTimeInterval:200.0]);

outputs "3:20".

NSDateComponentsFormatter *dateComponentsFormatter = [[NSDateComponentsFormatter alloc] init];
dateComponentsFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
dateComponentsFormatter.allowedUnits = (NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond);
NSLog(@"%@", [dateComponentsFormatter stringFromTimeInterval:200.0]);

outputs "0:03:20".

4
  • 2
    Nice update. But if it's really just such a simple calculation, wouldn't be using these object a huge overhead (as long as there is no dynamic format involved)? Commented Aug 28, 2015 at 17:08
  • 2
    you need the formatting to ensure the string appears correctly for different locales etc. Commented Apr 14, 2016 at 10:20
  • Really tiny comment, but it is weird to give an example of C function for ObjectiveC question. Probably worth changing it into ObjectiveC format?
    – Rilakkuma
    Commented May 24, 2016 at 6:56
  • Saved me a ton of code! This is how I used it for OrangeIRC.
    – ahyattdev
    Commented Dec 27, 2016 at 4:13
18

Swift 3 version of onmyway133's answer:

import Foundation

func format(_ duration: TimeInterval) -> String {
    let formatter = DateComponentsFormatter()
    formatter.zeroFormattingBehavior = .pad
    formatter.allowedUnits = [.minute, .second]

    if duration >= 3600 {
        formatter.allowedUnits.insert(.hour)
    }

    return formatter.string(from: duration)!
}


print(format(12)) // 0:12
print(format(65)) // 1:05
print(format(1750)) // 29:10
print(format(3890)) // 1:04:50
print(format(45720)) // 12:42:00
3
  • Is creating a DateComponentsFormatter expensive performancewise, like a DateFormatter or NumberFormatter?
    – Moshe
    Commented Sep 15, 2017 at 22:07
  • 1
    Instead of checking if there's an hour value, setting zeroFormattingBehavior to be [.dropLeading, .pad] might be a better (less code) option. Commented Oct 28, 2018 at 23:47
  • The comments appear to be incorrect. This code results in: 00:12, 01:05, 29:10, 01:04:50, 12:42:00
    – Jordan H
    Commented Jul 3, 2020 at 20:47
10

Some extra lines of code, but I feel using NSDateComponents will give a more precise value.

- (NSString *)getTimeRepresentationFromDate:(NSDate *)iDate withTimeInterval:(NSTimeInterval)iTimeInterval {
    NSString *aReturnValue = nil;
    NSDate *aNewDate = [iDate dateByAddingTimeInterval:iTimeInterval]; 

    unsigned int theUnits = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSCalendar *aCalender = [NSCalendar currentCalendar];
    NSDateComponents *aDateComponents = [aCalender components:theUnits fromDate:iDate toDate:aNewDate options:0];

    aReturnValue = [NSString stringWithFormat:@"%d:%d:%d", [aDateComponents hour], [aDateComponents minute], [aDateComponents second]];

    return aReturnValue;
}
5
  • The above method uses the 2 dates using which the TimeInterval is created. You can also pass [NSDate date] to iDate parameter as a default value.
    – Roshit
    Commented Nov 13, 2011 at 10:30
  • 2
    In what way is this "more precise" than the method used by @matthias-bauch?
    – j b
    Commented Jul 1, 2013 at 16:59
  • 1
    with this method u get time interval in seconds, hours , min i.e. in terms of 60 while @matthias-bauch's answer gives you in decimal terms for example if you wait for sufficient time you will see 1 min 79 sec instead of 2 min 19 sec
    – Ashish P
    Commented Jan 28, 2014 at 8:38
  • This is a much better solution than the accepted solution. The use of ":" is still a problem for internationalization, but at least this is robust across leap days and daylight savings boundaries.
    – evanflash
    Commented Aug 26, 2014 at 18:30
  • @AshishPisey The modulo operator prevents anything bigger than 59. Commented Oct 4, 2014 at 14:11
8

In Swift 2, iOS 8+. This makes sure we only show hour when necessary

func format(duration: NSTimeInterval) -> String {
  let formatter = NSDateComponentsFormatter()
  formatter.zeroFormattingBehavior = .Pad

  if duration >= 3600 {
    formatter.allowedUnits = [.Hour, .Minute, .Second]
  } else {
    formatter.allowedUnits = [.Minute, .Second]
  }

  return formatter.stringFromTimeInterval(duration) ?? ""
}

So you have

print(format(12)) // 0:12
print(format(65)) // 1:05
print(format(1750)) // 29:10
print(format(3890)) // 1:04:50
print(format(45720)) // 12:42:00
5

Swift 4

DateComponentsFormatter().string(from: <# TimeInterval #>)

ex:

DateComponentsFormatter().string(from: 59.0)
4
NSTimeInterval ti = 3667;
double hours = floor(ti / 60 / 60);
double minutes = floor((ti - (hours * 60 * 60)) / 60);
double seconds = floor(ti - (hours * 60 * 60) - (minutes * 60));
3

To "extend" Matthias Bauch's suggestion, in Swift I would make this a computed property of NSTimeInterval:

extension NSTimeInterval {
  var stringValue: String {
    let interval = Int(self)
    let seconds = interval % 60
    let minutes = (interval / 60) % 60
    let hours = (interval / 3600)
    return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
  }
}

The advantage of this is it's attached to the NSTimeInterval type, not your view controller or wherever else you put that function. To use you'd go something like:

let timeInterval = NSDate().timeIntervalSinceDate(start)        
self.elapsedTimeLabel.text = timeInterval.stringValue
1
  • Thanks, Kenny! In my case I needed them separately, so I added additional variables to your extension: "var seconds: Int { let interval = Int(self); let seconds = interval % 60; return seconds }" and so on for minutes and hours. So that usage will be: print("minutes spent: (timeInterval.minutes)")
    – Vitalii
    Commented Aug 19, 2016 at 13:07
2

Based on answer by @onmyway133 here is the Swift 4 version:

func format(duration: TimeInterval) -> String {
    let formatter = DateComponentsFormatter()
    formatter.zeroFormattingBehavior = .pad

    if duration >= 3600 {
        formatter.allowedUnits = [.hour, .minute, .second];
    } else {
        formatter.allowedUnits = [.minute, .second];
    }

    return formatter.string(from: duration) ?? "";
}
0

straight from apple docs: in h file:

 @property(strong,nonatomic)NSDateComponentsFormatter *timerFormatter;

in m file

@synthesize timerFormatter;

- (void)viewDidLoad {
[super viewDidLoad];
NSDateComponentsFormatter *timerFormatter = [[NSDateComponentsFormatter alloc] init];
timerFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional; 
//10:59 Positional THIS ONE DOES NOT SEEM TO WORK iOS<9 WHEN <1Minute JUST SHOWS 01, 10m 59s Abbreviated, 10min 59sec Short, 10minutes 59seconds Full ...
timerFormatter.allowedUnits = NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
}

whereever you need to convert your NSTimeInterval timeInterval to hh:mm:ss string, do this:

NSString *txt=[timerFormatter stringFromTimeInterval:timeInterval];
0

I guess, the timer fraction should be ceiled out. As Matthias' code was creating that issue in seconds, I use the following slightly modified from that of Matthias

    - (NSString *)stringFromTimeInterval:(NSTimeInterval)interval {
        int ti = (int) ceil(interval);
        int seconds = ti % 60;
        int minutes = (ti / 60) % 60;
        int hours = (ti / 3600);
        return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
    }
0

Objective C version of onmyway133's answer

- (NSString*) formatTimeInterval:(NSTimeInterval) timeInterval {

    NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];

    formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;

    if (timeInterval > 3600) {
        formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    } else {
        formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitSecond;
    }

    return [formatter stringFromTimeInterval:timeInterval];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.