Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a readable time from timeIntervalSinceDate in swift

Tags:

swift

nsdate

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.

like image 625
Leighton Avatar asked Nov 17 '14 23:11

Leighton


1 Answers

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.

like image 58
Jeff Avatar answered Sep 28 '22 10:09

Jeff