首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何检查两个NSDates是否来自同一天

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

Stack Overflow用户
提问于 2016-05-25 10:03:49
回答 2查看 29.2K关注 0票数 61

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

代码语言:javascript
复制
   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的值,以便被算作前一天,所以我肯定需要一些帮助。谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-25 10:18:20

实际上,NSCalendar有一个方法可以做你想做的事情!

代码语言:javascript
复制
/*
    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);

所以你可以这样使用它:

代码语言:javascript
复制
[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2];

或在Swift中

代码语言:javascript
复制
Calendar.current.isDate(date1, inSameDayAs:date2)
票数 182
EN

Stack Overflow用户

发布于 2016-05-25 10:08:26

您应该比较日期组件:

代码语言:javascript
复制
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")
}

或更短:

代码语言:javascript
复制
let diff = Calendar.current.dateComponents([.day], from: self, to: date)
if diff.day == 0 {
    print("same day")
} else {
    print("different day")
}
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37426662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档