LoginSignup
1
1

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-11-29
  • 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
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1