我试图将显示字符串的时间转换为Int。 语法看起来像这样,我想提取整数并乘以第一个,然后添加更晚以获得以分钟为单位的时间。
12h 10m
3h 14m
16h 0m
由于显示的字符串可以是hhmm,hmm,hhm或hm,因此我无法使用固定偏移量进行子字符串。 我试图通过首先找到"来对字符串进行子串。 "然后是m。 在其他语言中,这很容易,但是对于一些共鸣,我不能让它在swift中工作。
请帮助我,你是我唯一的希望。
答案 0 :(得分:1)
我认为在你的情况下最好将你有两次的字符串溢出
self.view.window
答案 1 :(得分:1)
由于您只需要使用日期/时间字符串进行操作,我认为您最好使用内置DateFormatter
进行操作
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH'h' mm'm'"
let date = dateFormatter.date(from: "2h 10m")!
let hour = Calendar.current.component(.hour, from: date)
// returns 2
let minutes = Calendar.current.component(.minute, from: date)
// returns 10
答案 2 :(得分:1)
您问题的最佳解决方案是
func getTime(time:String)->(Int,Int)
{
let arry = time.components(separatedBy: " ")
let hours = arry[0]
let min = arry[1]
let indexForHour = hours.index(hours.startIndex, offsetBy: (hours.characters.count - 1))
let indexForMin = min.index(min.startIndex, offsetBy: (min.characters.count - 1))
let hour = Int(hours.substring(to: indexForHour))
let minut = Int(min.substring(to: indexForMin))
return (hour!,minut!)
}
let str1 = "12h 10m"
let str2 = "3h 14m"
let str3 = "16h 0m"
let firstTime:(hour:Int,min:Int) = getTime(time:str1)
print(firstTime)
let secondTime:(hour:Int,min:Int) = getTime(time:str2)
print(secondTime)
let thirdTime:(hour:Int,min:Int) = getTime(time:str3)
print(thirdTime)
<强>输出强>
(小时:12,分:10)
(小时:3,分:14)
(小时:16,分:0)
答案 3 :(得分:1)
您可以使用组件(分隔:)获取时间组件(小时和分钟)并获取第一个组件(小时),将其乘以60并将最后一个组件(分钟)添加到其中。
extension String {
var minutes: Int {
var minutes = 0
if let hourChars = components(separatedBy: " ").first?.characters.dropLast(),
let hours = Int(String(hourChars)) {
minutes += hours * 60
}
if let minChars = components(separatedBy: " ").last?.characters.dropLast(),
let mins = Int(String(minChars)) {
minutes += mins
}
return minutes
}
}
测试
let str1 = "12h 10m"
let minutes1 = str1.minutes // 730
let str2 = "3h 14m"
let minutes2 = str2.minutes // 194
let str3 = "16h 0m"
let minutes3 = str3.minutes // 960