0

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!
MID
  • 3
  • 2
  • 1
    Please show your values for the original date, the converted string, the converted date and the time interval. – Martin R Apr 27 '15 at 18:33

1 Answers1

0

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)
Stefan Salatic
  • 4,513
  • 3
  • 22
  • 30