如何按日期过滤Struct数组?

时间:2015-11-04 19:30:16

标签: swift struct nsdate foundation

我有一个结构如:

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{($0.Date == TodayDate}

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

基于Martin R的评论和link你可以使用isDateInToday!这很简单

您可以尝试这样的事情:

let gregorianCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!

let TodayRows = RawDataFromDb.filter{
    return self.gregorianCalendar.isDateInToday($0.Date)
}

至于我喜欢使用的等同于:

extension NSDate: Comparable { }

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

如果您使用此功能而不是isDateInToday,则需要将Todaystruct.Date的小时数设置为12(以便比较日期)在白天节省的第一天登陆)和分钟/秒到零。由于小时,分钟和秒确实会影响比较。

例如:

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
}

答案 1 :(得分:1)

最简单的是,就在今天:

let calendar = NSCalendar.autoupdatingCurrentCalendar()

let targetData = rawData.filter({
  $0.date != nil && calendar.isDateInToday($0.date!)
})

任意一天:

let calendar = NSCalendar.autoupdatingCurrentCalendar()

let targetDate = NSDate(timeIntervalSince1970: 123456789)

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