如何将Swift3中的字符串以秒为单位更改为分钟?

问题描述:

嗨我正在获取作为一个字符串的时间值。我得到的数字是在几秒钟内。现在我想通过使用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) 
+0

看到这个答案:https://*.com/a/46667805/6257435 – DonMag

+0

@DonMag它不会将我的时间转换为09:00 –

+0

对不起,你可以用它作为起点......前三行将你的持续时间分为小时,分钟和秒......从这里开始,应该很简单字符串根据需要。 – DonMag

这里有一个方法:

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" 

这当然会根据语言环境而有所不同。

+0

它回到PM –

+0

我不明白你的评论...你没有得到字符串“00:00”吗? – DonMag

+0

是的,我得到了,但它是24小时格式,我需要12小时格式,我需要显示上午和下午随着它 –

您可以使用此:

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

你需要改进我做了什么 –

考虑使用雨燕瞬间框架:https://github.com/akosma/SwiftMoment

let duration: TimeInterval = 7200.0 
let moment = Moment(duration) 
let formattedDuration = "\(moment.minutes):\(moment.seconds)"