0

I need to compare two Date object to get the day difference between them, for example: 10/10 compares with today 10/7 will be 3, but the Date object returned to me from server is not aligned with the current time. There will be a few minutes difference which results in 10/10 being 2 days ahead of 10/7 because of the delay

I found a line of code that can give me a Date object of the current time, but I want to convert an existing Date object from somewhere else, how do I do it?

let today = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!

e.g. 2020-10-08 16:08:57.259580+0000 I want it to be 2020-10-08 00:00:00 +0000 something like this

Choi
  • 41
  • 5

1 Answers1

0

Don’t use midnight. Just parse your date string first. For calendrical calculations you should always use noon. First create a custom date format to parse your date string properly.

extension Formatter {
    static let iso8601: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = .init(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSSSSxx"
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        return formatter
    }()
}

Then create a helper to convert your date to noon time and another one to calculate the days between two dates and set them to noon:

extension Date {
    var noon: Date {
        Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
    }
    func days(from date: Date) -> Int {
        Calendar.current.dateComponents([.day], from: date.noon, to: noon).day!
    }
    var daysFromToday: Int { days(from: Date()) }
}

Playground testing:

let dateString = "2020-10-08 16:08:57.259580+0000"
let now = Date()  // "Oct 8, 2020 at 5:56 AM"
print(Formatter.iso8601.string(from: now))  // "2020-10-08 08:56:46.179000+0000\n"
if let date = Formatter.iso8601.date(from: dateString) {  // "Oct 8, 2020 at 1:08 PM"
    let days = Date().days(from: date)  // 0
}

let dateString = "2020-10-10 16:08:57.259580+0000"
if let date = Formatter.iso8601.date(from: dateString) {
    let days = date.daysFromToday  // 2
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571