69

I am struggling with this. I have a value in seconds that I want to display in a label in HH:MM format. I have searched the internet for ages and found some answers, but either not fully understood them, or they seem like an odd way of doing what I want. If someone could help me out on this one that would be great! Bear in mind that I am new to this games so this question may seem like a really basic one to the more experienced out there.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Stumf
  • 941
  • 1
  • 11
  • 26
  • Take a look at a [similar question I asked a while ago](http://stackoverflow.com/questions/1025192/memory-leaks-formatting-a-string-to-display-time-each-second) which also covers the aspect of memory and efficiency. – Jorge Israel Peña Nov 16 '09 at 00:29

6 Answers6

251

I was looking for the same thing that you are looking but couldn't find one. So I wrote one -

- (NSString *)timeFormatted:(int)totalSeconds
{

    int seconds = totalSeconds % 60; 
    int minutes = (totalSeconds / 60) % 60; 
    int hours = totalSeconds / 3600; 

    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds]; 
}

works perfectly in Swift as well:

 func timeFormatted(totalSeconds: Int) -> String {
    let seconds: Int = totalSeconds % 60
    let minutes: Int = (totalSeconds / 60) % 60
    let hours: Int = totalSeconds / 3600
    return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
 }
Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
Rohit Agarwal
  • 4,269
  • 3
  • 27
  • 22
  • Thanks for your answer, it looks like what I need, but can't seem to use it without errors. I am convinced the error is on my side. If you don't mind helping me further: My value is a float and it is in seconds. I have it displaying in a label when a button is pressed. Where would your code go, and how would I make my label display the value in the HH:MM format? Many thanks, Stu – Stumf Nov 18 '09 at 23:54
  • Sorted, thanks for your help. Your answer and http://stackoverflow.com/questions/1259028/convert-nsnumber-double-value-into-time answer by Pholker were the reason I could do this! Thanks again – Stumf Nov 20 '09 at 01:16
  • Great stuff -- made this a class method and rolled it into a category on NSString. Agree with bitcruncher, very clean. – Danilo Campos Jul 27 '10 at 06:14
  • Calculating minutes, why take the modulo of the division?!? `minutes = totalSeconds / 60`. Don't overcomplicate. – kadam Mar 06 '14 at 23:48
  • 1
    @kadam: Because there are 60 minutes in an hour. If you didn't have the modulo, your string would read "01:60:00" instead of "01:00:00" for 3600 seconds. –  Aug 16 '14 at 00:24
35

In iOS 8.0 and higher versions it can also be done with NSDateComponentsFormatter. I need to mention that it will format the string without first leading zero, for example '9:30', but not '09:30'. But if you like to use formatters, you can use this code:

-(NSString *)getTimeStringFromSeconds:(double)seconds
{
     NSDateComponentsFormatter *dcFormatter = [[NSDateComponentsFormatter alloc] init];
     dcFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
     dcFormatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute;
     dcFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
     return [dcFormatter stringFromTimeInterval:seconds];
}
edukulele
  • 489
  • 4
  • 11
10

This is how I do it:

-(NSString *)formatTimeFromSeconds:(int)numberOfSeconds
{

    int seconds = numberOfSeconds % 60;
    int minutes = (numberOfSeconds / 60) % 60;
    int hours = numberOfSeconds / 3600;

    //we have >=1 hour => example : 3h:25m
    if (hours) {
        return [NSString stringWithFormat:@"%dh:%02dm", hours, minutes];
    }
    //we have 0 hours and >=1 minutes => example : 3m:25s
    if (minutes) {
        return [NSString stringWithFormat:@"%dm:%02ds", minutes, seconds];
    }
    //we have only seconds example : 25s
    return [NSString stringWithFormat:@"%ds", seconds];
}
Mongi Zaidi
  • 1,043
  • 10
  • 15
7

For Swift:

func formatTimeInSec(totalSeconds: Int) -> String {
    let seconds = totalSeconds % 60
    let minutes = (totalSeconds / 60) % 60
    let hours = totalSeconds / 3600
    let strHours = hours > 9 ? String(hours) : "0" + String(hours)
    let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes)
    let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds)

    if hours > 0 {
        return "\(strHours):\(strMinutes):\(strSeconds)"
    }
    else {
        return "\(strMinutes):\(strSeconds)"
    }
}
akshay
  • 184
  • 2
  • 9
Aks
  • 8,181
  • 5
  • 37
  • 38
7

While @Aks' answer for Swift works, I'm a little skeptic about hardcoding values in my code. @edukulele's answer is much more cleaner but it's in Objective-C. I translated it to Swift with a slight change. I normally write my formatters as lazy vars.

private lazy var dateFormatter: NSDateComponentsFormatter = {
    let formatter = NSDateComponentsFormatter()
    formatter.zeroFormattingBehavior = .Pad
    formatter.allowedUnits = [.Hour, .Minute, .Second]
    formatter.unitsStyle = .Positional
    return formatter
}()
Community
  • 1
  • 1
Isuru
  • 30,617
  • 60
  • 187
  • 303
1

For Swift with clock count

    var timer = NSTimer()
    var count = 1
    func updateTime() {
        count++
        let seconds = count % 60
        let minutes = (count / 60) % 60
        let hours = count / 3600
        let strHours = hours > 9 ? String(hours) : "0" + String(hours)
        let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes)
        let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds)

        if hours > 0 {
            clockOutlet.text = "\(strHours):\(strMinutes):\(strSeconds)"
        }
        else {
            clockOutlet.text = "\(strMinutes):\(strSeconds)"
        }   
    }
Prudhvi
  • 2,276
  • 7
  • 34
  • 54
Perry C
  • 11
  • 2