在swift中添加时间字符串

时间:2015-11-09 12:17:12

标签: ios swift loops time substring

我有一系列timeStrings,格式如下:

x Hr(s)xx min。

我需要添加这些来总计。我想知道最好的方法是什么?

我的想法是找到“Hr(s)”的索引。然后,如果我在索引0和索引“Hr(s)”之间进行子串,我有我的hrs var然后将6加到索引“Hr(s)”并找到索引“min” - 1,给我最小变种

然后我需要考虑秒是否大于60.所以如果我把我的秒变量除以60并且答案大于1,我将答案添加到我的hrs var?

任何人都可以看到这种逻辑中的任何缺陷吗?

示例实施:

JSON回复:

    {"status":"OK","hrs":[{"scheduleDate":"2015-11-09","userName":"John Doe","company":"Company X","hrsWorked":"0 Hr(s) 42 min"},{"scheduleDate":"2015-11-10","userName":"Jane Doe","company":"Company Y","hrsWorked":"0 Hr(s) 47 min"},{"scheduleDate":"2015-11-10","userName":"Bob loblaw","company":"Company X","hrsWorked":"0 Hr(s) 37 min"},{"scheduleDate":"2015-11-10","userName":"Joe Soap","company":"Company Y","hrsWorked":"0 Hr(s) 50 min"},{"scheduleDate":"2015-11-10","userName":"Test","company":"Company Y","hrsWorked":"0 Hr(s) 40 min"}],"queryStatus":"OK","message":null,"count":5}

var hrsVar = 0
var minsVar = 0
loop through hrsArray{
    hrsMinStr = hrsWorkedInJson
    if let endHrsIndex = hrsMinStr.lowercaseString.characters.indexOf("Hr(s)") {
        print("Index: \(index)")
        let hrsStr = Int(hrsMinStr.substringWithRange(Range<String.Index>(start: 0, end: endHrsIndex)))

        hrsVar += hrsStr

        let minStr = Int(hrsMinStr.substringWithRange(Range<String.Index>(start: endHrsIndex + 1, end: hrsMinStr.length - 3)))
        minsVar += minStr

    }
}

if minsVar/60 > 1 {
   hrsVar = hrsVar + minsVar/60
   minsVar = minsVar%60
}

更新

似乎我无法传递“Hr(s)”而只传递一个字符“h”。因此,我试图使用advancedBy(x)方法来获得正确的endIndex。但是我收到了错误:

 Cannot invoke initializer for type 'Range<Index>' with an argument list of type '(start: Int, end: String.CharacterView.Index)'

更新的代码:

if let endHrsIndex = hrsMinStr.lowercaseString.characters.indexOf("h") {
   print("Index: \(endHrsIndex)")
   let hrsStr = Int(hrsMinStr.substringWithRange(Range<String.Index>(start: 0, end: endHrsIndex)))

   hrsVar += hrsStr

   let minStr = Int(hrsMinStr.substringWithRange(Range<String.Index>(start: endHrsIndex.advancedBy(5), end: hrsMinStr.length.characters.count.advancedBy(-3))))
   minsVar += minStr
}

我真的在寻找最有效的方法,所以请告知是否有更好的方法/如果您看到这种方法的问题

2 个答案:

答案 0 :(得分:0)

您应该尝试在您的情况下使用扫描仪。

        let string = "12 Hr(s) 37 min"
        let scanner = NSScanner(string: string)
        var min: Int = 0
        var hour : Int = 0
        scanner.scanInteger(&hour)
        scanner.scanString("Hr(s) ", intoString: nil)
        scanner.scanInteger(&min)

如果在Objective-C中创建此部件,则更容易:

        int min, hour;
        sscanf("12 Hr(s) 37 min", "%d Hr(s) %d min", &hour, &min);

答案 1 :(得分:0)

import Foundation
let str = "0 Hr(s) 42 min"
let time = str
    .stringByReplacingOccurrencesOfString("Hr(s)", withString:":")
    .stringByReplacingOccurrencesOfString("min", withString: "")
    .stringByReplacingOccurrencesOfString(" ", withString: "")
let t = time.characters.split(Character(":"))
let h = Int(String(t[0])) // 0
let m = Int(String(t[1])) // 1

和总和

import Foundation

var time: [(hours:Int,minutes:Int,seconds:Int)] = []
for i in 0...5 {
    let h = Int(arc4random_uniform(24))
    let m = Int(arc4random_uniform(60))
    let s = Int(arc4random_uniform(60))
    time.append((h,m,s))
}
let t = time.reduce(0) { (sum, time: (hours: Int, minutes: Int, seconds: Int)) -> Int in
    sum + time.seconds + time.minutes * 60 + time.hours * 60 * 60
}


let seconds = t % 60
let minutes = ((t - seconds) / 60) % 60
let hours = ((t - seconds) / 3660)

time.forEach {
    print(String(format: "     %6d:%02d:%02d", arguments: [$0.hours,$0.minutes, $0.seconds]))
}
print("-------------------")
print(String(format: "Sum: %6d:%02d:%02d", arguments: [hours,minutes,seconds]))
/*

         12:25:04
          2:43:36
         14:09:35
         11:59:43
         10:39:19
         23:32:14
-------------------
Sum:     74:29:31

*/