gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:00:01 30 4
gpt4 key购买 nike

您好,我遇到了与给定日期范围进行日期比较的问题场景,场景如下:

我有一个包含数据的数组:

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]

现在我有两个日期,它们给出了 fromto 两个日期示例:

var fromDate = "dd-MM-yyyy"
var toDate = "dd-MM-yyyy"

现在我想比较 filter1Date 变量数组与范围 fromDatetoDate 变量

由此我必须从 filter1Date 获取数据,这些数据介于这些日期之间,有人可以帮助我吗?

最佳答案

要比较两个 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
}
}

关于swift - 快速比较给定数组和两个日期范围的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30252558/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com