Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jrmsklar/1efcc88f93a7bda7c97c411a1bcec922 to your computer and use it in GitHub Desktop.
Save jrmsklar/1efcc88f93a7bda7c97c411a1bcec922 to your computer and use it in GitHub Desktop.
Swift NSTimeInterval extension that formats the time interval into a "X hr Y min" or "X min Y sec" string
//
// NSTimeInterval+HourMinuteSecondString.swift
// Companion
//
// Created by Josh Sklar on 4/26/16.
// Copyright © 2016 Companion. All rights reserved.
//
import Foundation
extension NSTimeInterval {
/// Returns a `String` representation of the hour/minute or minute/second
/// value of the receiver.
///
/// If the receiver is greater than 1 hour, will return "X hr X min".
/// If the receiver is less than 1 hour, will return "X min X sec".
var hourMinuteSecondString: String {
get {
let selfInSeconds = Int(self)
let hours = selfInSeconds / 3600
let hoursString = "hr"
let minutesString = "min"
let secondsString = "sec"
if hours >= 1 {
let minutes = (selfInSeconds % 3600) / 60
if minutes > 0 {
return "\(hours) \(hoursString) \(minutes) \(minutesString)"
}
else {
return "\(hours) \(hoursString)"
}
}
else {
let minutes = selfInSeconds / 60
if minutes >= 1 {
let seconds = selfInSeconds % 60
if seconds > 0 {
return "\(minutes) \(minutesString) \(seconds) \(secondsString)"
}
else {
return "\(minutes) \(minutesString)"
}
}
else {
return "\(selfInSeconds) \(secondsString)"
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment