MID
MID

Reputation: 3

Using NSTimeInterval after using dateFromString

I am working in swift and I am having trouble with NSDateFormatter and NSTimeInterval.

What I am trying to do is save a string representation of a date, then later convert it back to an NSDate object and then find the time interval between that date and the current time. This is giving me really strange answers, like making the time interval wrong. The dates themselves are correct when I print them out before, and the time interval methods work when I use them on normal dates, so I suspect that the problem is how I am converting the dates to strings and then back again. Below is some of the code:

saving the date:

       var date = NSDate()
       var dateformatter = NSDateFormatter()
       dateformatter.dateStyle = .ShortStyle
       dateformatter.timeStyle = .ShortStyle

       newContact.lastCallDate = dateformatter.stringFromDate(date)

retrieving the date and calculating the time interval:

    let dateformatter = NSDateFormatter()
    dateformatter.dateStyle = .ShortStyle
    dateformatter.timeStyle = .ShortStyle
    let date2 = dateformatter.dateFromString(newContact.lastCallDate)
    println(date2)

    let last = date2?.timeIntervalSince1970

    let current = NSDate().timeIntervalSince1970

    let timeElapsed = current - last!

Upvotes: 0

Views: 491

Answers (1)

Stefan Salatic
Stefan Salatic

Reputation: 4513

This method only saves minutes. My suggestion is to save it as time interval

var interval = NSDate().timeIntervalSince1970

And then load it up by adding that time to 1970 date like this

var date = NSDate(timeIntervalSince1970: interval)

Upvotes: 0

Related Questions