Peter71 Peter71 - 18 days ago 5
Swift Question

Swift: Compare date by days

I try to compare two days ignoring time. So I use

calendar.compare(date1, to: date2, toGranularity: .day)


BUT when transfering the string date to Date type, it is transformed to UTC. So it will be "moved" from 1.1.2016 0:05 to 31.12.2015 11:05 pm. When comparing daywise, this includes only the remaining hour. Before conversion it was 24 hours. Any idea to handle this issue without much effort?

Additionally:
The code:

var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm"
var date1 : Date = dateFormatter.date(from: "01-01-2016 00:05")!
var date2 = dateFormatter.date(from: "01-01-2016 03:30")

if let dateFromString = dateFormatter.date(from: "01-01-2016 00:05") {
print(dateFromString)
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let stringFromDate = dateFormatter.string(from: dateFromString)
}


Calendar.current.compare(date1, to: date2!, toGranularity: .day) == .orderedSame

Answer

Try this code:

var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

var date1 = dateFormatter.date(from:  "01-01-2016 00:05")
var date2 = dateFormatter.date(from:  "01-01-2016 03:30")

print("date1: \(date1!)")
print("date2: \(date2!)")

if Calendar.current.compare(date1!, to: date2!, toGranularity: .day) == .orderedSame {
    print("orderedSame")
}

result

enter image description here

Comments