Как проверить, являются ли два NSDate с одного дня
Я работаю над разработкой ios, и мне очень сложно проверить, есть ли два NSDate с одного дня. Я попытался использовать этот
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)
но он просто проверяет, имеет ли два NSDates разницу в 24 часа. Я думаю, что есть способ заставить его работать, но все же, я хочу, чтобы значения NSDate до 2 часов утра были засчитаны как накануне, поэтому мне определенно нужна помощь здесь. Спасибо!
Ответы
Ответ 1
NSCalendar имеет метод, который делает именно то, что вы хотите на самом деле!
/*
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);
Итак, вы использовали бы это так:
[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2];
Или в Swift
Calendar.current.isDate(date1, inSameDayAs:date2)
Ответ 2
Вы должны сравнить компоненты даты:
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")
}
Или короче:
let diff = Calendar.current.dateComponents([.day], from: self, to: date)
if diff.day == 0 {
print("same day")
} else {
print("different day")
}