will cohen will cohen - 1 year ago 64
iOS Question

Subtracting two different time formats in swift

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


@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")

Hello, I need to subtract the string, durationText, from the newDate. So for example, the duration text would be something like 1hr 12min and the new date would be something like 8:40 PM. How would I go about subtracting the 1hr 12min from 8:40 PM? Any suggestions would

Answer Source

So the only real part of the problem left for you is parsing a string like "1hr 12min" into a NSTimeInterval (Double). After that, you can use dateByAddingTimeInterval as in your sample code. You will need to be careful that these input strings such as "1hr 12min" are in a consistent format so you can parse them, but something like this could work for the given input:

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

//get the individual components
let hours:Double = Double(numberStrings[0])
let minutes:Double = Double(numberStrings[1])

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

Like I mentioned above, this relies on your durationTexts being in that format ([number]hr [number]min). You'll need to adjust this code if your strings come in formats that, for instance, contain seconds, or decimal values.