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

标签 ios swift nsdate

<分区>

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

   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 值算作前一天,所以我在这里绝对需要一些帮助。谢谢!

最佳答案

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)

关于ios - 如何检查两个 NSDates 是否来自同一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37426662/

相关文章:

ios - 循环 UICollectionview,如何保持所有单元格角度为 0°

swift - 如何正确连接GameScene.swift和GameScene.sks?

ios - 带有 cast 的快速可选链接

objective-c - NSDate 转 GMTDate 转 JSON 格式

ios - 为什么仅在 Real iphone 上从字符串创建日期失败?

android - Firebase:获取当前时间而不写入数据库(IOS 和 ANDROID)

ios - 将新单元格插入 Collection View

objective-c - 如果用户的 Facebook session 有效,如何重定向到另一个 View Controller ?

ios - [NSDate timeIntervalSinceReferenceDate] 上的 exc_bad_access

ios - UITableViewController : cellForRowAtIndexPath keeps looping through section 1