Skip to content

Instantly share code, notes, and snippets.

@cbess
Last active May 5, 2023 07:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbess/3286530e51b50b8a9884bed0ce8e0175 to your computer and use it in GitHub Desktop.
Save cbess/3286530e51b50b8a9884bed0ce8e0175 to your computer and use it in GitHub Desktop.
Swift: Seconds to minutes and hours parts
/// Represents parts of time
struct TimeParts: CustomStringConvertible {
var seconds = 0
var minutes = 0
/// The string representation of the time parts (ex: 07:37)
var description: String {
return NSString(format: "%02d:%02d", minutes, seconds) as String
}
}
/// Represents unset or empty time parts
let EmptyTimeParts = 0.toTimeParts()
extension Int {
/// The time parts for this integer represented from total seconds in time.
/// -- returns: A TimeParts struct that describes the parts of time
func toTimeParts() -> TimeParts {
let seconds = self
var mins = 0
var secs = seconds
if seconds >= 60 {
mins = Int(seconds / 60)
secs = seconds - (mins * 60)
}
return TimeParts(seconds: secs, minutes: mins)
}
/// The string representation of the time parts (ex: 07:37)
func asTimeString() -> String {
return toTimeParts().description
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment