简体   繁体   中英

Comparing two NSDates gives back false positives

So I am trying to compare a bunch of dates from my Database (Strings, which I convert to NSdates) with the current date.

When I run the code for an example date: 2016-07-17 12:28:51 +0000 it gives back false positives for the day before (yesterday).

Console output:

Optional(2016-07-15 22:00:00 +0000)
DAY IN THE PAST
Optional(2016-07-15 22:00:00 +0000)
DAY IN THE PAST
Optional(2016-07-16 22:00:00 +0000)
SAME DAY
Optional(2016-07-16 22:00:00 +0000)
SAME DAY
Optional(2016-07-16 22:00:00 +0000)
SAME DAY

I don't see what I'm doing wrong here. Code:

let dateToday = NSDate() // example: 2016-07-17 12:28:51 +0000
 print(dateToday)
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let openDB = realm.objects(Article)
        for item in openDB {
            let getItem = item.toDate
            let date = dateFormatter.dateFromString(getItem!)

            let order = NSCalendar.currentCalendar().compareDate(dateToday, toDate: date!,
                toUnitGranularity: .Day)
            print(date) //example 2016-07-17 22:00:00 +0000
            switch order {
            case .OrderedDescending:
                print("DAY IN THE PAST")
            case .OrderedAscending:
                print("FUTURE DATE")
            case .OrderedSame:
                print("SAME DAY")
            }

Please note that I only need to check the dates itself, I don't care about the time (hours, minutes).

You need to decide what result you need, and then code for that.

NSDate objects encode moments in time, anywhere on the planet. Internally they use GMT as their time base, but that is an implementation detail.

If you want to compare 2 dates to see if they fall on the same day you need to specify the time zone to use for the comparison. If I compare 11:02 PM and 12:02 PM in your time zone, GMT+2, those 2 dates fall on different days.

However, those times are 9:02 PM and 10:02 PM in GMT, and fall on the same day in GMT.

If you want to know if the dates are the same date in GMT then you need to create a gregorian calendar object and set it's time zone to GMT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM