我目前正在开发一个具有用户输入时间的应用程序,例如2 A.M. - 下午5点
有没有办法在军事时间(如2和17)将该字符串转换为两个整数?
答案 0 :(得分:1)
您可以使用componentsSeparatedByString拆分此String,将这2个字符串转换为NSString并从每个字符串中提取integerValue。如果结果小于12,您还需要在结果中添加12小时。如果是12点,您还需要返回0。
extension String {
var hour:Int {
var result = (self as NSString).integerValue
if contains(Array(lowercaseString).map{String($0)}, "p") {
result = result < 12 ? result + 12 : result
} else {
result = result == 12 ? 0 : result
}
return result
}
var hours:(from:Int, to:Int) {
return (componentsSeparatedByString("-").first!.hour,componentsSeparatedByString("-").last!.hour)
}
}
测试
let timeInput1 = "2 A.M. - 5 P.M."
let timeInput2 = "9 A.M. - 1 P.M."
timeInput1.hours // (.0 2, .1 17)
timeInput1.hours.from // 2
timeInput1.hours.to // 17
timeInput2.hours // (.0 9, .1 13)
timeInput2.hours.from // 9
timeInput2.hours.to // 13
答案 1 :(得分:0)
var input = "5AM"
var output = Int()
var firstCharacterOfString = input[advance(input.startIndex, 0)]
//search string for first character, return char
var characterToString:String = String(firstCharacterOfString)
//convert char to String
var StringToIntegar:Int = characterToString.toInt()!
//convert String to Int
if input.rangeOfString("PM") != nil{
//if input has "PM" in it perform this code
output = StringToIntegar + 12}
//add 12 to Int
else {//if input DOESN'T have "PM" in it perform this code
output = StringToIntegar}
注意:因为只搜索第一个字符
,所以不会为10,11,12工作