i Have an array of strings with the following format,
let sample_array = ["05:30","06:20","04:20","09:40"]
When after we converted all string
to DATE
format ,How can we find the total time from this array.
i Have an array of strings with the following format,
let sample_array = ["05:30","06:20","04:20","09:40"]
When after we converted all string
to DATE
format ,How can we find the total time from this array.
I think you can skip converting string to date for achieving your desired output:
let sample_array = ["05:30","06:20","04:20","09:40"]
var hours:Int = 0
var minutes:Int = 0
for timeString in sample_array {
let components = timeString.components(separatedBy: ":")
let hourComp = Int(components.first ?? "0") ?? 0
let minComp = Int(components.last ?? "0") ?? 0
hours += hourComp
minutes += minComp
}
hours += minutes/60
minutes = minutes%60
let hoursString = hours > 9 ? hours.description : "0\(hours)"
let minsString = minutes > 9 ? minutes.description : "0\(minutes)"
let totalTime = hoursString+":"+minsString
For your case, I would suggest to handle it without looking at it as dates. You could get your desired result by implementing a function as:
func getTotalTime(_ array: [String]) -> String {
// getting the summation of minutes and seconds
var minutesSummation = 0
var secondsSummation = 0
array.forEach { string in
minutesSummation += Int(string.components(separatedBy: ":").first ?? "0")!
secondsSummation += Int(string.components(separatedBy: ":").last ?? "0")!
}
// converting seconds to minutes
let minutesInSeconds = secondsToMinutes(seconds: secondsSummation).0
let restOfSeconds = secondsToMinutes(seconds: secondsSummation).1
return "\(minutesSummation + minutesInSeconds):\(restOfSeconds)"
}
// https://stackoverflow.com/questions/26794703/swift-integer-conversion-to-hours-minutes-seconds
func secondsToMinutes (seconds : Int) -> (Int, Int) {
return ((seconds % 3600) / 60, (seconds % 3600) % 60)
}
Therefore:
let array = ["20:40" , "20:40"]
let result = getTotalTime(array)
print(result) // 41:20
From the question and comments it seems that you are trying to calculate the total time (in hours and minutes) from the given array.
let sample_array = ["05:30","06:20","04:20","09:40"]
func getTime(arr: [String]) -> Int {
var total = 0
for obj in arr {
let comp = obj.split(separator: ":")
var hours = 0
var minutes = 0
if let hr = comp.first, let h = Int(String(hr)) {
hours = h * 60
}
if let mn = comp.last, let min = Int(String(mn)) {
minutes = min
}
total += hours
total += minutes
}
return total
}
let totalTime = getTime(arr: sample_array)
print(totalTime)
let hours = totalTime/60
let minutes = totalTime%60
print("\(hours) hours and \(minutes) minutes")
You can further calculates days, month and year also.
I hope it is what you want.