Hi,
How to convert the string "10h : 50m" to seconds?
Hi,
How to convert the string "10h : 50m" to seconds?
Whet is your problem ? Parsing the String or computing the value ?
How is this string formatted ? By a formatter ?
To find numberOfHours and numberOfSeconfs, you should
- search for "h", retain the part of string before
- search for m and retain the 2 chars before (which may be "15" or " 5" for instance)
Compute seconds :
sec = numberOfHours * 3600 + numberOfSeconfs * 60
Here sec = 36000 + 3000 = 39000
You can use regex for this ; it will be robust to variations as "9h: 50m" or 10h:5m" or even "10h: 5mn"
let timeStr = "10h : 50m"
var hours = 0
var minutes = 0
let patternH = "[0-9]+h"
let regexH = try! NSRegularExpression(pattern: patternH, options: .caseInsensitive)
if let match = regexH.firstMatch(in: timeStr, range: NSRange(0.. let hStr = String(timeStr[Range(match.range(at: 0), in: timeStr)!].dropLast())
hours = Int(hStr) ?? 0
} else {
print("No match")
}
let patternM = "[0-9]+m"
let regexM = try! NSRegularExpression(pattern: patternM, options: .caseInsensitive)
if let match = regexM.firstMatch(in: timeStr, range: NSRange(0.. let mStr = String(timeStr[Range(match.range(at: 0), in: timeStr)!].dropLast())
minutes = Int(mStr) ?? 0
} else {
print("No match")
}
let seconds = 3600 * hours + 60 * minutes
Whet is your problem ? Parsing the String or computing the value ?
How is this string formatted ? By a formatter ?
To find numberOfHours and numberOfSeconfs, you should
- search for "h", retain the part of string before
- search for m and retain the 2 chars before (which may be "15" or " 5" for instance)
Compute seconds :
sec = numberOfHours * 3600 + numberOfSeconfs * 60
Here sec = 36000 + 3000 = 39000
You can use regex for this ; it will be robust to variations as "9h: 50m" or 10h:5m" or even "10h: 5mn"
let timeStr = "10h : 50m"
var hours = 0
var minutes = 0
let patternH = "[0-9]+h"
let regexH = try! NSRegularExpression(pattern: patternH, options: .caseInsensitive)
if let match = regexH.firstMatch(in: timeStr, range: NSRange(0.. let hStr = String(timeStr[Range(match.range(at: 0), in: timeStr)!].dropLast())
hours = Int(hStr) ?? 0
} else {
print("No match")
}
let patternM = "[0-9]+m"
let regexM = try! NSRegularExpression(pattern: patternM, options: .caseInsensitive)
if let match = regexM.firstMatch(in: timeStr, range: NSRange(0.. let mStr = String(timeStr[Range(match.range(at: 0), in: timeStr)!].dropLast())
minutes = Int(mStr) ?? 0
} else {
print("No match")
}
let seconds = 3600 * hours + 60 * minutes