programing

NSTime에서 변환시간, 분, 초, 밀리초 단위의 swift 간격

bestprogram 2023. 8. 20. 12:19

NSTime에서 변환시간, 분, 초, 밀리초 단위의 swift 간격

내 코드는 다음과 같습니다.

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

출력에서 밀리초는 잘못된 결과를 제공합니다.밀리초를 정확하게 찾는 방법을 알려주세요.

Swift는 부동 소수점 숫자에 대한 나머지 계산을 지원하므로 다음을 사용할 수 있습니다.% 1.

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

다음과 같이:

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

결과:

stringFromTimeInterval(12345.67)                   "03:25:45.670"

스위프트 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)

        }
    }

사용:

self.timeLabel.text = player.duration.stringFromTimeInterval()

SWIFT 3 확장

이 방법이 각 조각의 출처를 더 쉽게 확인할 수 있기 때문에 필요에 따라 쉽게 수정할 수 있습니다.

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

iOS 8+, MacOS 10.10+용 Swift 3 솔루션(시간의 제로 패딩이 문제가 되지 않는 경우):

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"

@mathias-bauch 답변에 기초한 목표-C에서 동등합니다.

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

스위프트 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)

        }
    }

사용:

self.timeLabel.text = player.duration.stringFromTimeInterval()

대부분의 답변이 오래된 것 같습니다. 시간 간격을 나타내는 문자열을 표시하려면 항상 DateComponentsFormatter를 사용해야 합니다. 패딩 및 현지화를 처리하기 때문입니다.

스위프트 5.nums 및 일부 조건부 형식(0시간인 경우 시간을 표시하지 않음).

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

스위프트 4, 사용하지 않음.remainder(잘못된 값을 반환함):

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

@hixField의 swift 3 버전 답변, 현재 일 및 이전 날짜 처리:

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
    }

}

Swift 4(범위 확인 포함 - 충돌 없음)

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)

}
}

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
}

Swift 4 Extension - 나노초 정밀도

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

사용할 수 있습니다.Measurement그리고.UnitDuration변환TimeInterval값을 임의의 기간 단위로 지정합니다.필요한 결과를 밀리초 단위로 표시UnitDuration.millisecondsiOS 13.0, tvOS 13.0, watch OS 6.0 또는 macOS 10.15가 필요합니다.저는 해야 할 모든 조치를 취했습니다.func convertDurationUnitValueToOtherUnits(durationValue:durationUnit:smallestUnitDuration:)(스위프트 5.1.3/X 코드 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 }
}

다음과 같이 부를 수 있습니다.

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

보시다시피 결과를 얻기 위해 60과 1000과 같은 숫자 상수를 사용하지 않았습니다.

swift 2 확장자 + 변수 형식으로 변환:

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

}

여기 @maslovsa의 약간 개선된 버전이 있습니다.Precision입력 매개 변수:

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

및 용도:

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

언급URL : https://stackoverflow.com/questions/28872450/conversion-from-nstimeinterval-to-hour-minutes-seconds-milliseconds-in-swift