Reputation: 6867
Hi I have a problem scenario with date comparison with given date range the scenario is as follows:
I have an array containing data:
var filter1Date = [String]()
filter1Date[Wed, 06 May 2015 03:44:19 GMT, Wed, 06 May 2015 03:36:27 GMT, Wed, 06 May 2015 02:56:51 GMT, Wed, 06 May 2015 01:54:25 GMT, Tue, 05 May 2015 19:17:18 GMT, Wed, 06 May 2015 02:57:59 GMT, Wed, 06 May 2015 02:07:38 GMT, Wed, 06 May 2015 01:53:14 GMT, Tue, 05 May 2015 14:30:10 GMT, Tue, 05 May 2015 14:04:34 GMT]
Now I have two dates which gives from and to two dates example:
var fromDate = "dd-MM-yyyy"
var toDate = "dd-MM-yyyy"
now I want to compare array of filter1Date variable with range fromDate and toDate variable
from this I have to get data from filter1Date which ranges in between these dates can anybody help me in this?
Upvotes: 0
Views: 1487
Reputation: 11435
To compare two NSDates
you can use NSDate.compare()
method. I wrote an extension for the NSDate to handle this:
extension NSDate
{
func isInRange(from: NSDate, to:NSDate) -> Bool
{
if(self.compare(from) == NSComparisonResult.OrderedDescending || self.compare(from) == NSComparisonResult.OrderedSame)
{
if(self.compare(to) == NSComparisonResult.OrderedAscending || self.compare(to) == NSComparisonResult.OrderedSame)
{
// date is in range
return true
}
}
// date is not in range
return false
}
}
var dates:[NSDate] = ... // your dates array
var startDate:NSDate // your start range date
var endDate:NSDate // your end range date
for date in dates
{
if(date.isInRange(startDate, to: endDate))
{
//date is in range, do something
}
else
{
//date is not in range
}
}
Upvotes: 5