嗨我有一个问题场景,与给定日期范围的日期比较,场景如下:
我有一个包含数据的数组:
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]
现在我有两个日期,其中从和到两个日期 例如:
var fromDate = "dd-MM-yyyy"
var toDate = "dd-MM-yyyy"
现在我要将 filter1Date 变量的数组与范围 fromDate 和 toDate 变量进行比较
从这里我必须从 filter1Date 获取数据,这些日期之间的范围是否可以帮助我?
答案 0 :(得分:5)
要比较两个NSDates
,您可以使用NSDate.compare()
方法。我为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
}
}
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
}
}