Conversion from TimeInterval Type to mm:ss.ff String Type

Asked 1 years ago, Updated 1 years ago, 89 views

For example, the number timeInterval=124.04521142 is
02:04.04 I'd like to have a String type value of
Perhaps because I don't understand the format very well, I can see that it's a bit redundant even though I'm a beginner...

letmin=timeInterval/60
letsec=Int(timeInterval.truncatingRemainder(dividingBy:60))

let timeIntervalInteger=Int(timeInterval)
letdecimal=timeInterval-Double (timeIntervalInteger)
    // subtract only integers from the entire timeInterval and take only the decimal

letdecimalInteger=Int(decimal*100)
    // To remove the decimal "0.", round off the decimal point by 100 times

let minSec = String (format: "%02d:%02d%", min, sec)
    // First, put in mm:ss format

let miliSec=String (format: "%02d", decimalInteger)
    // Set milliseconds to ff format

var str = minSec + "." + miliSec

print(str)

I think it's a very roundabout way to subtract an integer part from timeInterval, multiply it by 100 times, and then add "%02d in the format "....

timeInterval should be treated as an integer increasing by one every 0.01 seconds in the timer, but what I want to deal with is the current playback time (currentPlaybackTime) of the song being played. I'm pulling it out as a TimeInterval type, so I want it to be a small number ->mm:ss.ff.

swift swift3

2022-09-30 20:21

1 Answers

First of all, this is not a direct answer to your question.You can convert a variable of type TimeInterval to a formatted string without having to create a new program.

// Keep the instance formatter somewhere (for example, as a class property).
var formatter=DateFormatter()
formatter.dateFormat="mm:ss.SS"

// A program that converts to a formatted string.
let timeInterval=124.04521142
let targetDate=Date(timeIntervalSinceReferenceDate:timeInterval)
let str = formatter.string (from:targetDate)

For more information, see the DateFormatter class, Date class reference.


2022-09-30 20:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.