如何检查两个NSDate是否来自同一天 [英] How to check if two NSDates are from the same day

查看:150
本文介绍了如何检查两个NSDate是否来自同一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on ios development and I find it really hard to check if two NSDates are from the same day. I tried to use this

   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)

,但它只是检查两个NSDate是否相差24小时.我认为有一种方法可以使它起作用,但仍然希望将凌晨2点之前的NSDate值算作前一天,因此,我在这里肯定需要一些帮助.谢谢!

but it just checks if two NSDates has a difference of 24 hours. I think there is a way to make it work but still, I wish to have NSDate values before 2 am in the morning to be count as the day before, so I definitely need some help here. Thanks!

推荐答案

NSCalendar提供了一种完全可以满足您实际需要的方法!

NSCalendar has a method that does exactly what you want actually!

/*
    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);

因此,您将像这样使用它:

So you'd use it like this:

[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2];

或者在Swift中

Calendar.current.isDate(date1, inSameDayAs:date2)

这篇关于如何检查两个NSDate是否来自同一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆