如何按日期过滤结构数组?

How to filter a Struct array by Date?

我有一个结构,例如:

struct AdData {
    var AdRequest = Int?()
    var Date = NSDate?() // eg: 2015-11-01 04:00:00 +0000
}

以及 AdData 的数组:

var RawDataFromDb = [AdData]()

我想找到 RawDataFromDbDate 匹配今天日期的所有项目。我想我必须以某种方式删除 AdData Date 组件的时间组件以仅比较日期,但我正在努力寻找一个优雅的解决方案。

到目前为止我试过了没有成功:

public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs === rhs || lhs.compare(rhs) == .OrderedSame
}

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedAscending
}

extension NSDate: Comparable { }


let TodayDate = NSDate()
let TodayRows = RawDataFromDb.filter{([=12=].Date == TodayDate}

感谢您的帮助!

根据 Martin R 的评论和 link 您可以只使用 isDateInToday!这很简单

您可以尝试这样的操作:

let gregorianCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!

let TodayRows = RawDataFromDb.filter{
    return self.gregorianCalendar.isDateInToday([=10=].Date)
}

至于equals comparable我喜欢用:

extension NSDate: Comparable { }

public func ==(leftDate: NSDate, rightDate: NSDate) -> Bool {
    return leftDate.isEqualToDate(rightDate)
}

如果您使用它,而不是 isDateInToday,您需要将 Todaystruct.Date 的小时数设置为 12(以便比较落在夏令时的第一天)和 minutes/seconds 归零。由于小时、分钟和秒确实会影响比较。

例如:

let gregorianCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let today: NSDate = gregorianCalendar.dateBySettingHour(12, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!

let TodayRows = RawDataFromDb.filter{
    let structDate = self.gregorianCalendar.dateBySettingHour(12, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!
    return structDate == self.today
}

最简单的,就在今天:

let calendar = NSCalendar.autoupdatingCurrentCalendar()

let targetData = rawData.filter({
  [=10=].date != nil && calendar.isDateInToday([=10=].date!)
})

任意一天:

let calendar = NSCalendar.autoupdatingCurrentCalendar()

let targetDate = NSDate(timeIntervalSince1970: 123456789)

let targetData = rawData.filter({
  [=11=].date != nil && calendar.isDate([=11=].date!, inSameDayAsDate: targetDate)
})