Q:

Why I am getting error on comparing two dates

I am trying to compare two dates, One is from server and other is my local device time.
This is code snippet.
let deviceDate = Date()

let calendar = Calendar.current
let dateNewServer = calendar.date(byAdding: .minute, value: 120, to: dateFromServer!)

//deviceDate -> 2019-06-25 08:28:03 +0000
//dateFromServer -> 2019-06-21 20:00:00 +0000
//dateNewServer -> 2019-06-21 22:00:00 +0000

if (deviceDate >= dateFromServer) && (deviceDate <= dateNewServer){
    print("Live Matches")
}else{
    print("Old/Upcoming Matches")
}

  

           

Error:
Binary operator '>=' cannot be applied to operands of type 'Date' and 'Date?'

A:

dateNewServer is an optional. So you need to unwrap it first before using further. This is the what your error says.

func date(byAdding component: Calendar.Component, value: Int, to date:
  Date, wrappingComponents: Bool = default) -> Date?

Solution: Unwrap it using optional binding(if let) or forced unwrapping(!). Optional binding is more safer way to unwrap an optional.
if let dateNewServer = calendar.date(byAdding: .minute, value: 120, to: dateFromServer) {
    if deviceDate.compare(dateFromServer) == .orderedDescending && deviceDate.compare(dateNewServer) == .orderedAscending {
        print("Live Matches")
    } else {
        print("Old/Upcoming Matches")
    }
}

