iOS
time
extension
Swift
stringOperation

String extension to show a time period e.g. "16.45 ~ 18.38 (1hr 53 mins)

  • Convert any time period to a formatted string, which is useful for e.g. journey time displays
  • Suffixes like "hr", "hrs", "mins" etc. are added if necessary.
  • These methods assume the start time is now. It is simple to add an arbitrary start time argument
extension String {

    public func durationStringFormatter(durationInSeconds: Double) -> String {
        let times = getFormattedStartEndTimes(duration: durationInSeconds) 
        let duration = getFormattedTimeSpan(duration: durationInSeconds)
        return times + " (" + duration + ")"
    }


    func getFormattedStartEndTimes(duration: Double) -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = .none
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "HH:mm"
        let start = formatter.string(from: Date())
        let end = formatter.string(from: Date().addingTimeInterval(duration))
        return start + " ~ " + end 
    }


    func getFormattedTimeSpan(duration: Double) -> String {
        let minutes: Double = duration / 60.0
        let hours = Int(floor( minutes / 60.0 ))
        var str = ""
        if(1 <= hours) {
            str.append(String(format: "%dhr", hours))
            if(1 < hours) {
                str.append("s")
            }
        }
        if(1.0 < minutes) {
            str.append((str.isEmpty ? "" : " ")) 
            str.append(String(format: "%dmins", Int(round(minutes)) - 60*hours))
        }
        if(str.isEmpty) {
            str = "<1min"
        }
        return str
    }
}