How to check if two NSDates are from the same day

IosSwiftNsdate

Ios Problem Overview


I am working on ios development and I find it really hard to check if two NSDates are from the same day. I tried to use this

   fetchDateList()
    // Check date
    let date = NSDate()
    // setup date formatter
    let dateFormatter = NSDateFormatter()
    // set current time zone
    dateFormatter.locale = NSLocale.currentLocale()
    
    let latestDate = dataList[dataList.count-1].valueForKey("representDate") as! NSDate
    //let newDate = dateFormatter.stringFromDate(date)
    let diffDateComponent = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: latestDate, toDate: date, options: NSCalendarOptions.init(rawValue: 0))
    print(diffDateComponent.day)

but it just checks if two NSDates has a difference of 24 hours. I think there is a way to make it work but still, I wish to have NSDate values before 2 am in the morning to be count as the day before, so I definitely need some help here. Thanks!

Ios Solutions


Solution 1 - Ios

NSCalendar has a method that does exactly what you want actually!

/*
	This API compares the Days of the given dates, reporting them equal if they are in the same Day.
*/
- (BOOL)isDate:(NSDate *)date1 inSameDayAsDate:(NSDate *)date2 NS_AVAILABLE(10_9, 8_0);

So you'd use it like this:

[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2];

Or in Swift

Calendar.current.isDate(date1, inSameDayAs:date2)

Solution 2 - Ios

You should compare the date components:

let date1 = NSDate(timeIntervalSinceNow: 0)
let date2 = NSDate(timeIntervalSinceNow: 3600)

let components1 = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: date1)
let components2 = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: date2)

if components1.year == components2.year && components1.month == components2.month && components1.day == components2.day {
	print("same date")
} else {
	print("different date")
}

Or shorter:

let diff = Calendar.current.dateComponents([.day], from: self, to: date)
if diff.day == 0 {
    print("same day")
} else {
    print("different day")
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshJoshJoshView Question on Stackoverflow
Solution 1 - IosCatfish_ManView Answer on Stackoverflow
Solution 2 - IosMike HendersonView Answer on Stackoverflow