Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.
  • 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
    }
}
cayozin
iOS/Android development (Swift/C++/Java/Kotlin/XML/Javascript), backend (php/mySQL) and Machine Learning (Python/Scala)
ayudante
いつもユーザー中心で技術者とコンサルタントがとことん考え抜く それがアユダンテです
https://ayudante.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした