如何检查两个NSDates是否来自同一天

时间:2016-05-25 02:03:49

标签: ios swift nsdate

我正在研究ios开发,我发现很难检查两个NSD是否来自同一天。我试着用这个

   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小时的差异。我认为有一种方法可以使它工作但是,我希望在早上凌晨2点之前将NSDate值计算为前一天,所以我肯定需要一些帮助。谢谢!

2 个答案:

答案 0 :(得分:123)

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)

答案 1 :(得分:9)

您应该比较日期组件:

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")
}