How do i convert Date to TimeInterval so I can use the if statements
24,786
Solution 1
You can directly access it through property timeIntervalSinceNow
of Date
also there is no need to use NSDate
in Swift 3 use directly Date
and date(from:)
method of DateFormatter
return instance of Date?
not NSDate?
.
let timeInterval = date.timeIntervalSinceNow
And you can get TimeInterval
between two dates using method timeIntervalSince(_:)
.
let timeInterval = date1.timeIntervalSince(date2)
Solution 2
Swift 3.0
You Need write code this:
let elapseTimeInSeconds = Date().timeIntervalSince(date as Date)
Strong!!! Date() or NSDate().timeIntervalSince(date as Date)
Author by
CRey
Updated on September 03, 2020Comments
-
CRey over 3 years
This is my code:
if let date = messages?.date{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mm a" //let elapseTimeInSeconds = NSDate.timeIntervalSince(date) let elapseTimeInSeconds = Date(timeIntervalSinceNow: (date as? Date)) let secondsInDays: TimeInterval = 60 * 60 * 24 if elapseTimeInSeconds > secondsInDays { dateFormatter.dateFormat = "EEE" } else if elapseTimeInSeconds > 7 * secondsInDays { dateFormatter.dateFormat = "MM/dd/yy" } timeLabel.text = dateFormatter.string(from: date as Date) }
this is the error:
Cannot convert value of type 'Date?' to expected argument type 'TimeInterval' (aka 'Double')
the error is on this line:
let elapseTimeInSeconds = Date(timeIntervalSinceNow: (date as? Date))
I've tried what I know and nothing has worked. Please help.
-
CRey over 7 yearsHey Nirav. Thank you for the quick answer. I had Date.TimeIntervalSince(date) before and its type was (Date) -> TimeInterval which made it so the types didn't match therefore I couldn't compare them in If statement. So you switched them around it made it work.
-
CRey over 7 yearsMy code works now but Its skipping If statement for days that are more than a day or seven days. Any suggestions?