Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 505
CRey Avatar asked Dec 23 '16 05:12

CRey


2 Answers

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)
like image 88
Nirav D Avatar answered Nov 12 '22 20:11

Nirav D


Swift 3.0

You Need write code this:

let elapseTimeInSeconds = Date().timeIntervalSince(date as Date) 

Strong!!! Date() or NSDate().timeIntervalSince(date as Date)
like image 33
Anton Russia Avatar answered Nov 12 '22 21:11

Anton Russia