Esqarrouth/EZSwiftExtensions

Date.timePassed() returns string with Optional(xx) in it.

kevinmann opened this issue · 3 comments

Using timePassed() on a date returns a string with Optional in it. For example:

        let format = "yyyy-MM-dd HH:mm:ss Z"
        let customDate = Date(fromString: "2017-02-15 00:40:48 +0000", format: format)
        
        if let customDateCheck:Date = customDate {
            print(customDateCheck.timePassed())
        }

The print from this shows as: Optional(17) hours ago

I can fix it crudely by adding ! to the returns in the function within DateExtensions.swift like this:

    public func timePassed() -> String {
        let date = Date()
        let calendar = Calendar.current
        let components = (calendar as NSCalendar).components([.year, .month, .day, .hour, .minute, .second], from: self, to: date, options: [])
        var str: String

        if components.year! >= 1 {
            components.year == 1 ? (str = "year") : (str = "years")
            return "\(components.year!) \(str) ago"
        } else if components.month! >= 1 {
            components.month == 1 ? (str = "month") : (str = "months")
            return "\(components.month!) \(str) ago"
        } else if components.day! >= 1 {
            components.day == 1 ? (str = "day") : (str = "days")
            return "\(components.day!) \(str) ago"
        } else if components.hour! >= 1 {
            components.hour == 1 ? (str = "hour") : (str = "hours")
            return "\(components.hour!) \(str) ago"
        } else if components.minute! >= 1 {
            components.minute == 1 ? (str = "minute") : (str = "minutes")
            return "\(components.minute!) \(str) ago"
        } else if components.second == 0 {
            return "Just now"
        } else {
            return "\(components.second!) seconds ago"
        }
    }

After that change the print for the code at the start correctly outputs like: 17 hours ago

Thanks, I will write a PR for this change by EOD.

This issue has been fixed and is now in master branch.