How to change the string in seconds to minutes in Swift3?

3.2k Views Asked by At

Hi I am getting the value of time as a string. The number which i am getting is in the seconds. Now i want to convert the Seconds to minutes by using swift3.

The Seconds which i am getting is: 540 this is in seconds.

Now i want to convert the seconds to the minutes. For example it should show as 09:00 .

How to achieve this using Swift3 code. Currently i am not using any conversion code.

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) 
3

There are 3 best solutions below

5
DonMag On BEST ANSWER

Here is one method:

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"

If you want your duration in seconds to be formatted as a "time of day," change the format string to:

formatter.dateFormat = "hh:mm:ss a"

Now, the resulting string should be:

"12:09:00 AM"

This will vary, of course, based on locale.

1
codejockie On

You can use this:

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
R OMS On

Consider using the Swift Moment framework: https://github.com/akosma/SwiftMoment

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