简体   繁体   English

快速比较给定数组和两个日期范围中的日期

[英]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现在我想将filter1Date变量数组与范围fromDatetoDate变量进行比较

from this I have to get data from filter1Date which ranges in between these dates can anybody help me in this?由此我必须从filter1Date获取这些日期之间的数据,有人可以帮助我吗?

To compare two NSDates you can use NSDate.compare() method.要比较两个NSDates您可以使用NSDate.compare()方法。 I wrote an extension for the NSDate to handle this:我为 NSDate 编写了一个扩展来处理这个问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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