[英]How to change the string in seconds to minutes in Swift3?
嗨,我正在获取字符串的时间值。 我得到的数字是在几秒钟内。 现在我想通过使用swift3将秒转换为分钟。
我得到的秒数是:540这是在几秒钟内。
现在我想将秒转换为分钟。 例如,应显示为09:00。
如何使用Swift3代码实现这一目标。 目前,我没有使用任何转换代码。
let duration: TimeInterval = 7200.0
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
formatter.allowedUnits = [ .hour, .minute, .second ] // Units to display in the formatted string
formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
let formattedDuration = formatter.string(from: duration)
这是一种方法:
let duration: TimeInterval = 540
// new Date object of "now"
let date = Date()
// create Calendar object
let cal = Calendar(identifier: .gregorian)
// get 12 O'Clock am
let start = cal.startOfDay(for: date)
// add your duration
let newDate = start.addingTimeInterval(duration)
// create a DateFormatter
let formatter = DateFormatter()
// set the format to minutes:seconds (leading zero-padded)
formatter.dateFormat = "mm:ss"
let resultString = formatter.string(from: newDate)
// resultString is now "09:00"
// if you want hours
// set the format to hours:minutes:seconds (leading zero-padded)
formatter.dateFormat = "HH:mm:ss"
let resultString = formatter.string(from: newDate)
// resultString is now "00:09:00"
如果您希望以秒为单位的持续时间格式设置为“一天中的时间”,请将格式字符串更改为:
formatter.dateFormat = "hh:mm:ss a"
现在,结果字符串应为:
"12:09:00 AM"
当然,这会因地区而异。
考虑使用Swift Moment框架: https : //github.com/akosma/SwiftMoment
let duration: TimeInterval = 7200.0
let moment = Moment(duration)
let formattedDuration = "\(moment.minutes):\(moment.seconds)"
您可以使用此:
func timeFormatter(_ seconds: Int32) -> String! {
let h: Float32 = Float32(seconds / 3600)
let m: Float32 = Float32((seconds % 3600) / 60)
let s: Float32 = Float32(seconds % 60)
var time = ""
if h < 10 {
time = time + "0" + String(Int(h)) + ":"
} else {
time = time + String(Int(h)) + ":"
}
if m < 10 {
time = time + "0" + String(Int(m)) + ":"
} else {
time = time + String(Int(m)) + ":"
}
if s < 10 {
time = time + "0" + String(Int(s))
} else {
time = time + String(Int(s))
}
return time
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.