web-dev-qa-db-fra.com

conversion de NSTimeInterval en heure, minutes, secondes et millisecondes en rapide

Mon code est ici:

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)
}

en sortie, les millisecondes donnent un résultat erroné. Merci de donner une idée de la manière de trouver les millisecondes correctement.

38
Lydia

Swift prend en charge les calculs de reste sur les nombres à virgule flottante, nous pouvons donc utiliser % 1

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

un péché: 

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)
}

résultat:

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)

        }
    }

Utilisation:

self.timeLabel.text = player.duration.stringFromTimeInterval()
90
Matthias Bauch

Swift 3 Extension  

Je pense qu’il est plus facile de voir d’où vient chaque pièce et de la modifier plus facilement.

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"
        }
    }
}
21
Jake Cronin

Équivalent en Objective-C, basé sur la réponse @ matthias-bauch.

+ (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];
}
16
Minos

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)

        }
    }

Utilisation:

self.timeLabel.text = player.duration.stringFromTimeInterval()
9
Mohammad Razipour

Solution Swift 3 pour iOS 8+, macOS 10.10+ si le zéro-remplissage des heures n'a pas d'importance:

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"
8
vadian

Swift 4, sans utiliser le .remainder (qui renvoie des valeurs incorrectes):

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)
}
6
mirap

pour convertir les heures et les minutes en secondes dans 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
}
3
Pablo Ruan

Je pense que la plupart de ces réponses sont obsolètes, vous devriez toujours utiliser DateComponentsFormatter si vous souhaitez afficher une chaîne représentant un intervalle de temps, car elle gérera le remplissage et la localisation pour vous.

3
lilpit

Swift 4 (avec contrôle de la plage ~ sans crash)

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)

}
}
2
maslovsa

La version Swift 3 de la réponse @hixField, maintenant avec les jours et les dates de traitement précédentes:

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
    }

}
2
Ohad Cohen

converti dans une extension Swift 2 + format variable:

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)
    }

}
0
HixField

Swift 4 Extension - avec une précision de nanosecondes

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
    }
}
0
Mick