Skip to content

Instantly share code, notes, and snippets.

@raunakp
Last active September 1, 2019 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raunakp/dbb5d713834b7ac3b18e33e33cf1fa9f to your computer and use it in GitHub Desktop.
Save raunakp/dbb5d713834b7ac3b18e33e33cf1fa9f to your computer and use it in GitHub Desktop.
TimeInterval+playbackString.swift
extension TimeInterval {
var playbackString: String {
if self.isNaN {
return "??"
}
var seconds = self
var mins = Int((seconds / 60).rounded(.down))
seconds = seconds.truncatingRemainder(dividingBy: 60)
let hours = mins / 60
mins = mins % 60
var str = ""
if mins == 0 && hours == 0 {
str = String(format: "%.2fs", seconds)
} else {
str = String(format: "%02d:%02d", mins, Int(seconds))
if hours > 0 {
let hoursPart = String(format: "%d:", hours)
str = hoursPart + str
}
}
return str
}
}
@raunakp
Copy link
Author

raunakp commented Sep 1, 2019

print(TimeInterval(2).playbackString)
// 2.00s
print(TimeInterval(62).playbackString)
// 01:02
print(TimeInterval(3762).playbackString)
// 1:02:42

print(TimeInterval(213762).playbackString)
// 1:02:42

@raunakp
Copy link
Author

raunakp commented Sep 1, 2019

print(TimeInterval(Double.nan).playbackString)
// ??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment