Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
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) {
        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
Help us understand the problem. What is going on with this article?
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
iOS/Android development (Swift/C++/Java/Kotlin/XML/Javascript), backend (php/mySQL) and Machine Learning (Python/Scala)
いつもユーザー中心で技術者とコンサルタントがとことん考え抜く それがアユダンテです


No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
Help us understand the problem. What is going on with this article?