-
-
Save shakemno/af07ba75dd543027e8f7d52a401fdd95 to your computer and use it in GitHub Desktop.
TimeFormatter Swift 2.0 - Convert milliseconds to a formatted output string of hours:minutes:seconds with applied padding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// TimeFormatter.swift | |
// ElectroDeluxe-Swift2.0 | |
// | |
// Convert milliseconds to a formatted output string containing hours:minutes:seconds | |
// with padding zero. | |
// | |
// Created by c0d3r on 21/08/15. | |
// Copyright © 2015 srmds. All rights reserved. | |
// | |
import Foundation | |
//Custom extension method to append Strings | |
extension String { | |
mutating func append(str: String) { | |
self = self + str | |
} | |
} | |
class TimeFormatter { | |
func getFormattedDurationString(trackDuration: NSNumber?) -> String { | |
guard let trackDuration = trackDuration where trackDuration.doubleValue > 1000.0 else { | |
let message = "trackDuration.doubleValue is lower then 1000.0 therefore reverting to 00:00:00" | |
print (message) | |
#warning(message) | |
return "00:00:00" | |
} | |
let milliseconds = trackDuration.doubleValue | |
var seconds = milliseconds / 1000; | |
var minutes = seconds / 60; | |
seconds %= 60; | |
let hours = minutes / 60; | |
minutes %= 60; | |
var timeComponents = Dictionary<String,NSNumber>() | |
timeComponents = ["hours":Int(hours), "minutes":Int(minutes),"seconds":Int(seconds)] | |
return self.durationStringBuilder(timeComponents) | |
} | |
private func durationStringBuilder(timeComponents:NSDictionary?) -> String { | |
var result:String = "" | |
guard let timeComponents = timeComponents where timeComponents.count == 3 else { | |
return result | |
} | |
let hours = setZeroPadding(timeComponents["hours"] as? Int, delimiter: false) | |
let minutes = setZeroPadding(timeComponents["minutes"] as? Int, delimiter: false) | |
let seconds = setZeroPadding(timeComponents["seconds"] as? Int, delimiter: true) | |
result.append(hours) | |
result.append(minutes) | |
result.append(seconds) | |
return result | |
} | |
private func setZeroPadding(timeComponent: Int?, delimiter: Bool) -> String { | |
var result:String = "" | |
guard let timeComponent = timeComponent where timeComponent > 0 else { | |
if !delimiter { | |
result.append("00:") | |
return result | |
} else { | |
result.append("00") | |
return result | |
} | |
} | |
if(timeComponent < 10){ | |
if !delimiter { | |
result.append("0\(timeComponent):") | |
} else{ | |
result.append("0\(timeComponent)") | |
} | |
} else { | |
if !delimiter { | |
result.append("\(timeComponent):") | |
} else{ | |
result.append("\(timeComponent)") | |
} | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment