programing

Swift - 시/분/초로 정수 변환

linuxpc 2023. 4. 16. 14:41
반응형

Swift - 시/분/초로 정수 변환

Swift에서의 시간 변환에 관한 기본적인 질문이 있습니다.

Hours / Minutes / Seconds로 변환할 정수가 있습니다.

예를 들어: Int = 27005다음 정보를 얻을 수 있습니다.

7 Hours  30 Minutes 5 Seconds

PHP로 하는 방법은 알지만 안타깝게도 swift는 PHP가 아닙니다.

정의

func secondsToHoursMinutesSeconds(_ seconds: Int) -> (Int, Int, Int) {
    return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}

사용하다

> secondsToHoursMinutesSeconds(27005)
(7,30,5)

또는

let (h,m,s) = secondsToHoursMinutesSeconds(27005)

위 함수는 Swift 튜플을 사용하여 한 번에 세 개의 값을 반환합니다.태플을 디스트럭처음부터let (var, ...)또는 필요에 따라 개별 태플멤버에 액세스 할 수 있습니다.

만약 당신이 실제로 그것을 인쇄해야 한다면Hours다음과 같은 것을 사용합니다.

func printSecondsToHoursMinutesSeconds(_ seconds: Int) {
  let (h, m, s) = secondsToHoursMinutesSeconds(seconds)
  print ("\(h) Hours, \(m) Minutes, \(s) Seconds")
}

상기의 실장은,secondsToHoursMinutesSeconds()에 효과가 있다Int논쟁들.필요한 경우Double반환값을 결정해야 하는 버전 - 이 될 수 있습니다.(Int, Int, Double)또는 그럴 수도 있다(Double, Double, Double)다음과 같은 것을 시도해 볼 수 있습니다.

func secondsToHoursMinutesSeconds(seconds: Double) -> (Double, Double, Double) {
  let (hr,  minf) = modf(seconds / 3600)
  let (min, secf) = modf(60 * minf)
  return (hr, min, 60 * secf)
}

MacOS 10.10 이상 / iOS 8.0 이상(NS)DateComponentsFormatter는 가독성 있는 문자열을 작성하기 위해 도입되었습니다.

사용자의 로케일과 언어를 고려합니다.

let interval = 27005

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .full

let formattedString = formatter.string(from: TimeInterval(interval))!
print(formattedString)

사용 가능한 유닛 스타일은 다음과 같습니다.positional,abbreviated,short,full,spellOut그리고.brief.

상세한 것에 대하여는, 메뉴얼을 참조해 주세요.

Vadian의 답변을 바탕으로, 나는 확장자를 썼다.Double(그 중)TimeInterval는 타입 에일리어스)로, time 형식의 문자열을 출력합니다.

extension Double {
  func asString(style: DateComponentsFormatter.UnitsStyle) -> String {
    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute, .second, .nanosecond]
    formatter.unitsStyle = style
    return formatter.string(from: self) ?? ""
  }
}

여기 다양한 것들이 있습니다.DateComponentsFormatter.UnitsStyle옵션은 다음과 같습니다.

10000.asString(style: .positional)  // 2:46:40
10000.asString(style: .abbreviated) // 2h 46m 40s
10000.asString(style: .short)       // 2 hr, 46 min, 40 sec
10000.asString(style: .full)        // 2 hours, 46 minutes, 40 seconds
10000.asString(style: .spellOut)    // two hours, forty-six minutes, forty seconds
10000.asString(style: .brief)       // 2hr 46min 40sec

Swift 5의 경우:

    var i = 9897

    func timeString(time: TimeInterval) -> String {
        let hour = Int(time) / 3600
        let minute = Int(time) / 60 % 60
        let second = Int(time) % 60

        // return formated string
        return String(format: "%02i:%02i:%02i", hour, minute, second)
    }

함수를 호출하려면

    timeString(time: TimeInterval(i))

02:44:57 반환

모든 것을 단순화하고 Swift 3에 필요한 코드의 양을 줄이기 위해 기존 답변의 매시업을 구축했습니다.

func hmsFrom(seconds: Int, completion: @escaping (_ hours: Int, _ minutes: Int, _ seconds: Int)->()) {

        completion(seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)

}

func getStringFrom(seconds: Int) -> String {

    return seconds < 10 ? "0\(seconds)" : "\(seconds)"
}

사용방법:

var seconds: Int = 100

hmsFrom(seconds: seconds) { hours, minutes, seconds in

    let hours = getStringFrom(seconds: hours)
    let minutes = getStringFrom(seconds: minutes)
    let seconds = getStringFrom(seconds: seconds)

    print("\(hours):\(minutes):\(seconds)")                
}

인쇄:

00:01:40

보다 구조화/유연한 접근방식을 다음에 제시하겠습니다.(Swift 3)

struct StopWatch {

    var totalSeconds: Int

    var years: Int {
        return totalSeconds / 31536000
    }

    var days: Int {
        return (totalSeconds % 31536000) / 86400
    }

    var hours: Int {
        return (totalSeconds % 86400) / 3600
    }

    var minutes: Int {
        return (totalSeconds % 3600) / 60
    }

    var seconds: Int {
        return totalSeconds % 60
    }

    //simplified to what OP wanted
    var hoursMinutesAndSeconds: (hours: Int, minutes: Int, seconds: Int) {
        return (hours, minutes, seconds)
    }
}

let watch = StopWatch(totalSeconds: 27005 + 31536000 + 86400)
print(watch.years) // Prints 1
print(watch.days) // Prints 1
print(watch.hours) // Prints 7
print(watch.minutes) // Prints 30
print(watch.seconds) // Prints 5
print(watch.hoursMinutesAndSeconds) // Prints (7, 30, 5)

이와 같은 접근방식을 사용하면 다음과 같은 편리한 해석을 추가할 수 있습니다.

extension StopWatch {

    var simpleTimeString: String {
        let hoursText = timeText(from: hours)
        let minutesText = timeText(from: minutes)
        let secondsText = timeText(from: seconds)
        return "\(hoursText):\(minutesText):\(secondsText)"
    }

    private func timeText(from number: Int) -> String {
        return number < 10 ? "0\(number)" : "\(number)"
    }
}
print(watch.simpleTimeString) // Prints 07:30:05

순수하게 Integer 기반 접근법은 윤일/초를 고려하지 않습니다.실제 날짜/시간을 다루는 경우 날짜 및 달력을 사용해야 합니다.

Swift 5:

extension Int {

    func secondsToTime() -> String {

        let (h,m,s) = (self / 3600, (self % 3600) / 60, (self % 3600) % 60)

        let h_string = h < 10 ? "0\(h)" : "\(h)"
        let m_string =  m < 10 ? "0\(m)" : "\(m)"
        let s_string =  s < 10 ? "0\(s)" : "\(s)"

        return "\(h_string):\(m_string):\(s_string)"
    }
}

사용방법:

let seconds : Int = 119
print(seconds.secondsToTime()) // Result = "00:01:59"

스위프트 4

func formatSecondsToString(_ seconds: TimeInterval) -> String {
    if seconds.isNaN {
        return "00:00"
    }
    let Min = Int(seconds / 60)
    let Sec = Int(seconds.truncatingRemainder(dividingBy: 60))
    return String(format: "%02d:%02d", Min, Sec)
}

X코드 12.1스위프트 5

Date ComponentsFormatter:unitsStyle을 사용하면 원하는 문자열을 얻을 수 있으며 allowedUnits를 언급할 수 있습니다.

예: unitsStyle:: 10000초 출력

  1. full = "2시간 46분 49초"
  2. 위치 = "2:46:40"
  3. 약어 = "2h 46m 40s"
  4. 맞춤법 = "2시간 46분 40초"
  5. 짧은 = "2시간 46분 40초"
  6. brief = "2시간 46분 40초"

사용하기 쉬움:

 let time = convertSecondsToHrMinuteSec(seconds: 10000)


func convertSecondsToHrMinuteSec(seconds:Int) -> String{
     let formatter = DateComponentsFormatter()
     formatter.allowedUnits = [.hour, .minute, .second]
     formatter.unitsStyle = .full
    
     let formattedString = formatter.string(from:TimeInterval(seconds))!
     print(formattedString)
     return formattedString
    }

SWIFT 3.0 솔루션은 대략 위의 확장 기능을 기반으로 합니다.

extension CMTime {
  var durationText:String {
    let totalSeconds = CMTimeGetSeconds(self)
    let hours:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 86400) / 3600)
    let minutes:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60)
    let seconds:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 60))

    if hours > 0 {
        return String(format: "%i:%02i:%02i", hours, minutes, seconds)
    } else {
        return String(format: "%02i:%02i", minutes, seconds)
    }

  }
}

AVPlayer가 이렇게 호출할 때 사용합니까?

 let dTotalSeconds = self.player.currentTime()
 playingCurrentTime = dTotalSeconds.durationText

다음은 Swift3의 또 다른 간단한 구현입니다.

func seconds2Timestamp(intSeconds:Int)->String {
   let mins:Int = intSeconds/60
   let hours:Int = mins/60
   let secs:Int = intSeconds%60

   let strTimestamp:String = ((hours<10) ? "0" : "") + String(hours) + ":" + ((mins<10) ? "0" : "") + String(mins) + ":" + ((secs<10) ? "0" : "") + String(secs)
   return strTimestamp
}

같은 질문에 답했습니다만, 밀리초를 표시할 필요는 없습니다.따라서 이 솔루션에는 iOS 10.0, tvOS 10.0, watchOS 3.0 또는 macOS 10.12가 필요합니다.

요.func convertDurationUnitValueToOtherUnits(durationValue:durationUnit:smallestUnitDuration:)여기서 이미 언급한 답변에서 나온 것입니다.

let secondsToConvert = 27005
let result: [Int] = convertDurationUnitValueToOtherUnits(
    durationValue: Double(secondsToConvert),
    durationUnit: .seconds,
    smallestUnitDuration: .seconds
)
print("\(result[0]) hours, \(result[1]) minutes, \(result[2]) seconds") // 7 hours, 30 minutes, 5 seconds

@r3dm4n의 답변은 훌륭했습니다.하지만 나도 시간이 필요했다.다른 누군가가 필요할 경우를 대비해서 다음과 같이 하십시오.

func formatSecondsToString(_ seconds: TimeInterval) -> String {
    if seconds.isNaN {
        return "00:00:00"
    }
    let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
    let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
    let hour = Int(seconds / 3600)
    return String(format: "%02d:%02d:%02d", hour, min, sec)
}

Swift 5 & String Response (표시 가능한 형식)

public static func secondsToHoursMinutesSecondsStr (seconds : Int) -> String {
      let (hours, minutes, seconds) = secondsToHoursMinutesSeconds(seconds: seconds);
      var str = hours > 0 ? "\(hours) h" : ""
      str = minutes > 0 ? str + " \(minutes) min" : str
      str = seconds > 0 ? str + " \(seconds) sec" : str
      return str
  }

public static func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
        return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
 }

사용방법:

print(secondsToHoursMinutesSecondsStr(seconds: 20000)) // Result = "5 h 33 min 20 sec"

GoZoner의 답변에 따르면 시간, 분, 초를 기준으로 시간을 포맷하기 위해 Extension을 작성했습니다.

extension Double {

    func secondsToHoursMinutesSeconds () -> (Int?, Int?, Int?) {
        let hrs = self / 3600
        let mins = (self.truncatingRemainder(dividingBy: 3600)) / 60
        let seconds = (self.truncatingRemainder(dividingBy:3600)).truncatingRemainder(dividingBy:60)
        return (Int(hrs) > 0 ? Int(hrs) : nil , Int(mins) > 0 ? Int(mins) : nil, Int(seconds) > 0 ? Int(seconds) : nil)
    }

    func printSecondsToHoursMinutesSeconds () -> String {

        let time = self.secondsToHoursMinutesSeconds()

        switch time {
        case (nil, let x? , let y?):
            return "\(x) min \(y) sec"
        case (nil, let x?, nil):
            return "\(x) min"
        case (let x?, nil, nil):
            return "\(x) hr"
        case (nil, nil, let x?):
            return "\(x) sec"
        case (let x?, nil, let z?):
            return "\(x) hr \(z) sec"
        case (let x?, let y?, nil):
            return "\(x) hr \(y) min"
        case (let x?, let y?, let z?):
            return "\(x) hr \(y) min \(z) sec"
        default:
            return "n/a"
        }
    }
}

let tmp = 3213123.printSecondsToHoursMinutesSeconds() // "892 hr 32 min 3 sec"

Swift 4+의 뮤직 플레이어에 사용하는 것은 다음과 같습니다. Int를 읽을 수 있는 문자열 형식으로 변환합니다.

extension Int {
    var toAudioString: String {
        let h = self / 3600
        let m = (self % 3600) / 60
        let s = (self % 3600) % 60
        return h > 0 ? String(format: "%1d:%02d:%02d", h, m, s) : String(format: "%1d:%02d", m, s)
    }
}

다음과 같이 사용:

print(7903.toAudioString)

★★★★★2:11:43

최신 코드: XCode 10.4 Swift 5

extension Int {
    func timeDisplay() -> String {
        return "\(self / 3600):\((self % 3600) / 60):\((self % 3600) % 60)"
    }
}

@Gamec 답변에서

typealias CallDuration = Int

extension CallDuration {
    func formatedString() -> String? {
        let hours = self / 3600
        let minutes = (self / 60) % 60
        let seconds = self % 60
        if hours > 0 { return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds) }
        return String(format: "%0.2d:%0.2d", minutes, seconds)
    }
}


사용방법:

let duration: CallDuration = 3000
duration.formatedString() // 50 minute

가장 간단한 방법:

let hours = time / 3600
let minutes = (time / 60) % 60
let seconds = time % 60
return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds)

NSTimeIntervalDouble연장해서 해 주세요.를를: :

extension Double {

    var formattedTime: String {

        var formattedTime = "0:00"

        if self > 0 {

            let hours = Int(self / 3600)
            let minutes = Int(truncatingRemainder(dividingBy: 3600) / 60)

            formattedTime = String(hours) + ":" + (minutes < 10 ? "0" + String(minutes) : String(minutes))
        }

        return formattedTime
    }
}

숫자를 문자열로서 시간으로 변환하다

func convertToHMS(number: Int) -> String {
  let hour    = number / 3600;
  let minute  = (number % 3600) / 60;
  let second = (number % 3600) % 60 ;
  
  var h = String(hour);
  var m = String(minute);
  var s = String(second);
  
  if h.count == 1{
      h = "0\(hour)";
  }
  if m.count == 1{
      m = "0\(minute)";
  }
  if s.count == 1{
      s = "0\(second)";
  }
  
  return "\(h):\(m):\(s)"
}
print(convertToHMS(number:3900))

(Swift 3에서) 종료했습니다.

let (m, s) = { (secs: Int) -> (Int, Int) in
        return ((secs % 3600) / 60, (secs % 3600) % 60) }(299)

그러면 m = 4, s = 59가 됩니다.원하는 대로 포맷할 수 있습니다.물론 추가 정보는 아니더라도 몇 시간을 추가할 수도 있습니다.

Swift 4 이 내선번호를 사용하고 있습니다.

 extension Double {

    func stringFromInterval() -> String {

        let timeInterval = Int(self)

        let millisecondsInt = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
        let secondsInt = timeInterval % 60
        let minutesInt = (timeInterval / 60) % 60
        let hoursInt = (timeInterval / 3600) % 24
        let daysInt = timeInterval / 86400

        let milliseconds = "\(millisecondsInt)ms"
        let seconds = "\(secondsInt)s" + " " + milliseconds
        let minutes = "\(minutesInt)m" + " " + seconds
        let hours = "\(hoursInt)h" + " " + minutes
        let days = "\(daysInt)d" + " " + hours

        if daysInt          > 0 { return days }
        if hoursInt         > 0 { return hours }
        if minutesInt       > 0 { return minutes }
        if secondsInt       > 0 { return seconds }
        if millisecondsInt  > 0 { return milliseconds }
        return ""
    }
}

사용법

// assume myTimeInterval = 96460.397    
myTimeInteval.stringFromInterval() // 1d 2h 47m 40s 397ms

Neek의 답은 틀렸습니다.

여기 올바른 버전이 있습니다.

func seconds2Timestamp(intSeconds:Int)->String {
   let mins:Int = (intSeconds/60)%60
   let hours:Int = intSeconds/3600
   let secs:Int = intSeconds%60

   let strTimestamp:String = ((hours<10) ? "0" : "") + String(hours) + ":" + ((mins<10) ? "0" : "") + String(mins) + ":" + ((secs<10) ? "0" : "") + String(secs)
   return strTimestamp
}

또 다른 방법은 초를 현재까지 변환하여 구성 요소를 날짜 자체로부터 초, 분, 시간 단위로 변환하는 것입니다.이 솔루션에는 23:59:59까지만 제한이 있습니다.

언급URL : https://stackoverflow.com/questions/26794703/swift-integer-conversion-to-hours-minutes-seconds

반응형