5

I'm trying to figure out how to get a readable time amount from timeIntervalSinceDate. Right now I have an NSDate with key "punchInTime" stored in NSUserDefaults, but I don't know how to get a readable time back when I want to find the difference between the stored NSDate "punchInTime" and the current time. I have:

var totalWorkTime = NSDate.timeIntervalSinceDate(punchInTime)

I'd like to interpolate "totalWorkTime" into a string to have readable time amounts.

Any help appreciated! Thanks.

Leighton
  • 6,559
  • 7
  • 21
  • 28
  • possible duplicate of [Swift - Integer conversion to Hours/Minutes/Seconds](http://stackoverflow.com/questions/26794703/swift-integer-conversion-to-hours-minutes-seconds) – zisoft Nov 18 '14 at 07:09
  • Do you want to know Hour minutes and seconds or the total of the highest unit like 10 seconds, 10 minutes, 10 hours, 10 days and so on? – Leo Dabus Dec 05 '14 at 20:21

1 Answers1

8

Fix your syntax. It should be:

var totalWorkTime = NSDate().timeIntervalSinceDate(punchInTime)

Note the parenthesis after NSDate. If you do not use parenthesis, and you try to treat totalWorkTime as an NSTimeInterval you will get the error Cannot invoke [operator] with an argument list of type ...

enter image description here

You can get a better error message if you specify the type in the variable assignment. The error is (x) -> y is not convertible to y

enter image description here

Swift is a functional language. Without the parenthesis after NSDate then totalWorkTime is not a symbol for a mere NSTimeInterval type, but rather it is a symbol for a function that takes an NSDate and returns a NSTimeInterval. This syntax in a playground shows:

enter image description here

Other than what I wrote above, zisoft is correct about this question (almost) being a duplicate. The other minor exception is that this question is asking about a Double (NSTimeInterval) type and the earlier question is asking about Int.

Jeff
  • 3,829
  • 1
  • 31
  • 49