Swift : Filtering NSDate by time intervals

417 views Asked by At

I have an array with NSDate() that the user adds with a datePicker, then this dates need to be filtered by current week, current month and year. I have tried using NSCalendar but I couldn't make it work. I want to group this NSDates in different arrays depending on the time interval that they are in.

1

There are 1 answers

2
FreeNickname On

One way is to simply use NSPredicate:

NSArray *arrayOfDates = @[
                    [NSDate dateWithTimeIntervalSince1970:0],
                    [NSDate dateWithTimeIntervalSince1970:100],
                    [NSDate dateWithTimeIntervalSince1970:200]
                   ];

NSDate *leftLimit = [NSDate dateWithTimeIntervalSince1970:50];
NSDate *rightLimit = [NSDate dateWithTimeIntervalSince1970:150];
NSPredicate *dateIntervalPredicate = [NSPredicate predicateWithFormat:@"self > %@ && self < %@", leftLimit, rightLimit];
NSArray *result = [array filteredArrayUsingPredicate:dateIntervalPredicate];
NSLog(@"Result: %@", result);

Of course, you can wrap it into a function, it's just an example.