puks1978
puks1978

Reputation: 3697

Convert decimal to hours:minutes:seconds

I am storing numbers in a MySQL DB as doubles so I can get min, max and sums.

I have a decimal number 1.66777777778 which equals 01:40:04 however I am wanting to be able to convert this decimal in to hour:minutes:seconds in Swift so I can display the value as 01:40:04 however I don't know how.

I have done some searching but most results are calculators without explanation.

I have this function to convert to decimal:

func timeToHour(hour: String, minute:String, second:String) -> Double
{
    var hourSource = 0.00
    if hour == ""
    {
        hourSource = 0.00
    }
    else
    {
        hourSource = Double(hour)!
    }
    let minuteSource = Double(minute)!
    let secondSource = Double(second)!

    let timeDecimal: Double = hourSource + (minuteSource / 60) + (secondSource / 3600)
    return timeDecimal
}

but need one to go back the other way.

Thanks

Upvotes: 1

Views: 2103

Answers (1)

David Berry
David Berry

Reputation: 41246

Try:

func hourToString(hour:Double) -> String {
    let hours = Int(floor(hour))
    let mins = Int(floor(hour * 60) % 60)
    let secs = Int(floor(hour * 3600) % 60)

    return String(format:"%d:%02d:%02d", hours, mins, secs)
}

Basically break each component out and concatenate them all together.

Upvotes: 4

Related Questions