How to convert an NSTimeInterval (seconds) into minutes

前端 未结 12 928
轮回少年
轮回少年 2020-11-28 01:27

I\'ve got an amount of seconds that passed from a certain event. It\'s stored in a NSTimeInterval data type.

I want to convert it into

相关标签:
12条回答
  • 2020-11-28 01:40

    How I did this in Swift (including the string formatting to show it as "01:23"):

    let totalSeconds: Double = someTimeInterval
    let minutes = Int(floor(totalSeconds / 60))
    let seconds = Int(round(totalSeconds % 60))        
    let timeString = String(format: "%02d:%02d", minutes, seconds)
    NSLog(timeString)
    
    0 讨论(0)
  • 2020-11-28 01:43

    Here's a Swift version:

    func durationsBySecond(seconds s: Int) -> (days:Int,hours:Int,minutes:Int,seconds:Int) {
        return (s / (24 * 3600),(s % (24 * 3600)) / 3600, s % 3600 / 60, s % 60)
    }
    

    Can be used like this:

    let (d,h,m,s) = durationsBySecond(seconds: duration)
    println("time left: \(d) days \(h) hours \(m) minutes \(s) seconds")
    
    0 讨论(0)
  • 2020-11-28 01:44

    All of these look more complicated than they need to be! Here is a short and sweet way to convert a time interval into hours, minutes and seconds:

    NSTimeInterval timeInterval = 326.4;
    long seconds = lroundf(timeInterval); // Since modulo operator (%) below needs int or long
    
    int hour = seconds / 3600;
    int mins = (seconds % 3600) / 60;
    int secs = seconds % 60;
    

    Note when you put a float into an int, you get floor() automatically, but you can add it to the first two if if makes you feel better :-)

    0 讨论(0)
  • 2020-11-28 01:44

    Since it's essentially a double...

    Divide by 60.0 and extract the integral part and the fractional part.

    The integral part will be the whole number of minutes.

    Multiply the fractional part by 60.0 again.

    The result will be the remaining seconds.

    0 讨论(0)
  • 2020-11-28 01:45

    Remember that the original question is about a string output, not pseudo-code or individual string components.

    I want to convert it into the following string: "5:26"

    Many answers are missing the internationalization issues, and most doing the math computations by hand. All just so 20th century...

    Do not do the Math yourself (Swift 4)

    let timeInterval: TimeInterval = 326.4
    let dateComponentsFormatter = DateComponentsFormatter()
    dateComponentsFormatter.unitsStyle = .positional
    if let formatted = dateComponentsFormatter.string(from: timeInterval) {
        print(formatted)
    }
    

    5:26


    Leverage on libraries

    If you really want individual components, and pleasantly readable code, check out SwiftDate:

    import SwiftDate
    ...
    if let minutes = Int(timeInterval).seconds.in(.minute) {
        print("\(minutes)")
    }
    

    5


    Credits to @mickmaccallum and @polarwar for adequate usage of DateComponentsFormatter

    0 讨论(0)
  • 2020-11-28 01:49

    If you're targeting at or above iOS 8 or OS X 10.10, this just got a lot easier. The new NSDateComponentsFormatter class allows you to convert a given NSTimeInterval from its value in seconds to a localized string to show the user. For example:

    Objective-C

    NSTimeInterval interval = 326.4;
    
    NSDateComponentsFormatter *componentFormatter = [[NSDateComponentsFormatter alloc] init];
    
    componentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
    componentFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;
    
    NSString *formattedString = [componentFormatter stringFromTimeInterval:interval];
    NSLog(@"%@",formattedString); // 5:26
    

    Swift

    let interval = 326.4
    
    let componentFormatter = NSDateComponentsFormatter()
    
    componentFormatter.unitsStyle = .Positional
    componentFormatter.zeroFormattingBehavior = .DropAll
    
    if let formattedString = componentFormatter.stringFromTimeInterval(interval) {
        print(formattedString) // 5:26
    }
    

    NSDateCompnentsFormatter also allows for this output to be in longer forms. More info can be found in NSHipster's NSFormatter article. And depending on what classes you're already working with (if not NSTimeInterval), it may be more convenient to pass the formatter an instance of NSDateComponents, or two NSDate objects, which can be done as well via the following methods.

    Objective-C

    NSString *formattedString = [componentFormatter stringFromDate:<#(NSDate *)#> toDate:<#(NSDate *)#>];
    NSString *formattedString = [componentFormatter stringFromDateComponents:<#(NSDateComponents *)#>];
    

    Swift

    if let formattedString = componentFormatter.stringFromDate(<#T##startDate: NSDate##NSDate#>, toDate: <#T##NSDate#>) {
        // ...
    }
    
    if let formattedString = componentFormatter.stringFromDateComponents(<#T##components: NSDateComponents##NSDateComponents#>) {
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题