Search code examples
iosswiftxcodensdateformatter

How do i convert Date to TimeInterval so I can use the if statements


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.


Solution

  • 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)