判斷兩個時間是不是同一天,是沒法用時間戳對比的,兩個時間戳間隔在24小時以內不能表明是同一天。ios
用時間戳對比,也是要計算是否同一年,同一月,同一日,才能判斷出是否同一天。macos
因此一般對比兩個時間是用 NSDate 來對比,可是要注意:NSDate 的時間實際上有某個時區的時間的含義,經過 [NSDate date] 建立出來的時間默認是零時區時間,可是這並不意味着兩個 NSDate 比較(判斷是否同一天)就必定會有正確的結果。網絡
NSDate 比較是不是同一天,本質是比較 NSDateComponents 的 day month year 是否都相等。spa
好比:code
- (BOOL)isSameDayWithDate:(NSDate *)date
{
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlag = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *comp1 = [calendar components:unitFlag fromDate:self];
NSDateComponents *comp2 = [calendar components:unitFlag fromDate:date];
return (([comp1 day] == [comp2 day]) && ([comp1 month] == [comp2 month]) && ([comp1 year] == [comp2 year]));
}
複製代碼
網絡上不少文章都介紹對 NSDate 或者 NSCalendar 作了擴展,來判斷某個日期是不是今天、昨天、明天。實際上 NSCalendar 在 ios(8.0) 開始提供了幾個官方方法。component
- (BOOL)isDateInToday:(NSDate *)date;
- (BOOL)isDateInYesterday:(NSDate *)date;
- (BOOL)isDateInTomorrow:(NSDate *)date;
複製代碼
可是考慮到用戶是能夠修改手機時間的,一般咱們會使用 ntp 時間做爲標準時間,而不直接使用手機時間。it
NSCalendar 也有提供了一個方法能夠直接對比兩個時間。io
/*
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 API_AVAILABLE(macos(10.9), ios(8.0), watchos(2.0), tvos(9.0));
複製代碼
可是,在實際場景中,比較兩個 NSDate 是不是同一天的時候,一般須要兩個 NSDate 同時處於當地時區纔有意義。class
一樣的兩個時間,在一個時區是同一天,在另外一個時區極可能不是同一天!!!擴展
若是你在東八區,用兩個零時區的時間來對比,是會出很大的問題的。
舉個例子:
today 1553741981 零時區 2019-03-28 02:59:41 +0000 (東八區 2019-03-28 10:59:41)
day 1553788800 零時區 2019-03-28 15:59:59 +0000 (東八區 2019-03-29 00:00:00)
複製代碼