2017-10-19 20 views
0

嗨我正在獲取作爲一個字符串的時間值。我得到的數字是在幾秒鐘內。現在我想通過使用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://stackoverflow.com/a/46667805/6257435 – DonMag

+0

@DonMag它不會將我的時間轉換爲09:00 –

+0

對不起,你可以用它作爲起點......前三行將你的持續時間分爲小時,分鐘和秒......從這裏開始,應該很簡單字符串根據需要。 – DonMag

回答

1

這裏有一個方法:

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小時格式,我需要顯示上午和下午隨着它 –

0

您可以使用此:

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

你需要改進我做了什麼 –

1

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

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