ios - swift 减去两种不同的时间格式

标签 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")

最佳答案

因此留给您的问题的唯一真实部分是将像“1hr 12min”这样的字符串解析为 NSTimeInterval (Double)。之后,您可以像示例代码中那样使用 dateByAddingTimeInterval。您需要注意这些输入字符串(例如“1hr 12min”)采用一致的格式,以便您可以解析它们,但对于给定的输入,类似这样的内容可能有效:

编辑:因为您似乎希望“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)。如果您的字符串采用的格式(例如,包含秒或小数值),则您需要调整此代码。

关于ios - swift 减去两种不同的时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38331812/

相关文章:

ios - 点击单元格显示下面的 View

swift - 为文本字段 swift 4 设置字符数和字符类型限制

ios - 查询 HealthKit 的相关性,但使用 anchor

java - System.nanoTime() 似乎损坏了。需要检查代码效率的替代方案

php - 设置文件的日期和时间

ios - 我现在还需要两个 Storyboard 文件来使用 Universal Storyboard 管理不同的设备吗?

ios - Google 的收件箱是否有 iOS 邮件方案 url?

ios - 如何在 iOS 上检测罗盘校准开关状态

ios - 为 UITextField 弹出键盘时 UIView 消失

php - 如何在用 PHP 提交表单时添加日期和时间?