我有一个(有点?)关于Swift中的时间转换的基本问题。

我有一个整数,我想转换成小时/分钟/秒。

示例:Int = 27005会给我:

7 Hours  30 Minutes 5 Seconds

我知道如何在PHP中做到这一点,但是,唉,swift不是PHP。


当前回答

以下是我在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

其他回答

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
}

将数字转换为字符串形式的时间

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 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中)。

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

这样m = 4 s = 59。你可以根据自己的喜好来设置格式。如果没有更多的信息,你当然也想增加工作时间。

Xcode 12.1。Swift 5

DateComponentsFormatter:创建字符串表示的格式化程序, 通过使用unitsStyle,你可以得到一个你想要的字符串,并提到allowedUnits。 例如:output for unitsStyle:: for 10000秒

满=“2小时46分49秒” 位置= "2:46:40" 缩写为"2h 46m 40s" 拼写= " 2小时46分40秒" 短=“2小时46分40秒” 简短= "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
    }