简体   繁体   中英

Compare dates from given array and two date ranges swift

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?

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
    }
}

You can then use it like this:

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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM