Mr.MIHIR Mr.MIHIR - 1 month ago 20
iOS Question

difference between two time interval ios components swift 3

I have two time interval basically i want to convert find out difference between them this is my code. but, its not works

func dateformatter(date:Double) -> String {

let timeElapsed:TimeInterval = TimeInterval(Int(date))
let timeNow:TimeInterval = TimeInterval(integerLiteral: Int64(Date().timeIntervalSince1970*1000))

let date2:Date = Date(timeIntervalSince1970: timeElapsed )
let date1:Date = Date(timeIntervalSince1970: timeNow )

let calender:Calendar = Calendar.current
let components:DateComponents = calender.dateComponents([.year, .month, .day, .hour, .minute], from: date1, to: date2)
var returnString:String = ""
print(components.second)
if components.second! < 60 {
returnString = "Just Now"
}else if components.minute! >= 1{
returnString = String(describing: components.minute) + " min ago"
}else if components.hour! >= 1{
returnString = String(describing: components.hour) + " hour ago"
}else if components.day! >= 1{
returnString = String(describing: components.day) + " days ago"
}else if components.month! >= 1{
returnString = String(describing: components.month)+" month ago"
}else if components.year! >= 1 {
returnString = String(describing: components.year)+" year ago"
}
return returnString
}

Answer

There is no need for all the conversion you doing at the beginning of the function. Date(timeIntervalSince1970:) accepts NSTimeInterval, however, it is only a typealias for double.

Also, because your first if statement check for seconds you need to include .seconds to the component parameter list.

Your could do the following:

func dateformatter(date: Double) -> String {

    let date1:Date = Date() // Same you did before with timeNow variable
    let date2: Date = Date(timeIntervalSince1970: date)

    let calender:Calendar = Calendar.current
    let components: DateComponents = calender.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date1, to: date2)
    print(components)
    var returnString:String = ""
    print(components.second)
    if components.second! < 60 {
        returnString = "Just Now"
    }else if components.minute! >= 1{
        returnString = String(describing: components.minute) + " min ago"
    }else if components.hour! >= 1{
        returnString = String(describing: components.hour) + " hour ago"
    }else if components.day! >= 1{
        returnString = String(describing: components.day) + " days ago"
    }else if components.month! >= 1{
        returnString = String(describing: components.month)+" month ago"
    }else if components.year! >= 1 {
        returnString = String(describing: components.year)+" year ago"
    }
    return returnString
}