Comparing date string with NSPredicate

二次信任 提交于 2021-01-29 17:34:34

问题


I was wondering if there's anyway to filter a set using NSPredicate sorted by date, where the date is an NSString in MMMM dd (i.e. March 24) format (it's NOT an NSDate.).


回答1:


If you are storing the date as a string in CoreData, the predicate is simple.

    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"theDate like %@", theDateString];

But I'm guessing that the date is stored as an NSDate object. Look into using NSDateFormatter to convert your string to an NSDate.

NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMMM dd"];
NSDate* theDate = [df dateFromString:theDateString];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SomeDate >= %@", theDate];



回答2:


You need to convert it to a NSDate first, which you can achieve with the predicateWithBlock function of NSPredicate. Convert the object and test it in your predicate block. I have never personally used it, so this answer is theoretical.




回答3:


Comparing NSDate or date in an NSArray with NSPredicate in Swift.

In Swift 2.1 or 2.0:

//format data
let Formata_Data = NSDateFormatter()
Formata_Data.calendar = NSCalendar.currentCalendar()
Formata_Data.dateFormat = "dd/MM/yyyy"
let _data_filtro = Formata_Data.stringFromDate(dias_filtros!)
let _data_hoje = Formata_Data.stringFromDate(NSDate())

let data_filtro_ns = Formata_Data.dateFromString(_data_filtro)

print("DATA.... \(_data_filtro)")

var predicate_Data = NSPredicate(block: { (data_string, Orcs) -> Bool in
    return data_filtro_ns?.earlierDate(Formata_Data.dateFromString(data_string) as! String)!) == data_filtro_ns
})
var array_filtro_dias = Orcamentos.filteredArrayUsingPredicate(predicate_Data)
Orcamentos = array_filtro_dias


来源:https://stackoverflow.com/questions/9864630/comparing-date-string-with-nspredicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!