在swift中减去两种不同的时间格式

时间:2016-07-12 14:32:09

标签: ios swift time

           NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) in
            // Get data as string
            if let object = try? NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject] {
                let rows = object["rows"] as! [[String:AnyObject]]
                let elements = rows.first!["elements"] as! [[String:AnyObject]]
                let duration = elements.first!["duration"] as! [String:AnyObject]
                let durationText = duration["text"] as! String
                print("duration for NY : \(durationText)")
            }

        }).resume()

   @IBAction func onDateChanged(sender: AnyObject) {
    let dateFormatter = NSDateFormatter()
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle


    let timeinterval = NSTimeInterval.abs(17 * 60) // ====================================== EDIT TO INCORPORATE TRAVEL TIME OF TWO DISTANCES =====================
    let newDate = datePicker.date.dateByAddingTimeInterval(-timeinterval)
    let strDate = dateFormatter.stringFromDate(newDate)

    print("\(strDate) is the date on the datePicker @willcohen")

您好,我需要从newDate中减去字符串durationText。因此,例如,持续时间文本将类似于1小时12分钟,新日期将类似于下午8:40。我怎样才能从晚上8:40减去1小时12分钟?任何建议

编辑:

           NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) in
            // Get data as string
            if let object = try? NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject] {
                let rows = object["rows"] as! [[String:AnyObject]]
                let elements = rows.first!["elements"] as! [[String:AnyObject]]
                let duration = elements.first!["duration"] as! [String:AnyObject]
                let durationText = duration["text"] as! String
                print("duration for NY : \(durationText)")

                let numberStrings = durationText.componentsSeparatedByCharactersInSet(
                    NSCharacterSet.decimalDigitCharacterSet().invertedSet).filter
                    { $0.characters.count > 0 }

                let hours:Double = Double(numberStrings[0])!
                let minutes:Double = Double(numberStrings[1])!

                self.durationTime = (hours * 3600) + (minutes * 60)
                print("\(self.durationTime) is the duration time")

                let dateFormatter = NSDateFormatter()
                dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
                self.newDate = self.datePicker.date.dateByAddingTimeInterval(self.durationTime)

                let strDate = dateFormatter.stringFromDate(self.newDate)
                print("\(strDate) is the time you should leave at @willcohen")

1 个答案:

答案 0 :(得分:1)

因此,问题的唯一真正部分是解析一个字符串,如" 1小时12分钟"进入NSTimeIntervalDouble)。之后,您可以在示例代码中使用dateByAddingTimeInterval。你需要注意这些输入字符串,如" 1小时12分钟和#34;是一致的格式,所以你可以解析它们,但这样的东西可以适用于给定的输入:

编辑:因为看起来你想要" x分钟"也是一个可能的输入,我调整了下面的代码:

//split the string by all non-number characters (leaving just the numbers)
let numberStrings = durationText.componentsSeparatedByCharactersInSet(
        NSCharacterSet.decimalDigitCharacterSet().invertedSet).filter 
        { $0.characters.count > 0 }

//get the individual components
let hours:Double
let minutes:Double
if numberStrings.count == 1 {
    hours = 0
    minutes = Double(numberStrings[0])
}
else {
    hours = Double(numberStrings[0])
    minutes = Double(numberStrings[1])
}

//make the NSTimeInterval
let duration:NSTimeInterval = (hours * 3600) + (minutes * 60)

就像我上面提到的,这取决于你的durationTexts采用那种格式([number]hr [number]min)。如果您的字符串格式为例如包含秒或十进制值,则需要调整此代码。