我正在尝试为语句创建一个多项来测试数组的两个值。我有一个NSDate类型的数组,从核心数据中保存了多个日期。我的目标是从数组中获取日期,如果日期是在一个独特的日子,则将它们添加到新数组中。我想检查数组中的项目,如果它们具有相同的日期,则不将它们添加到新数组中。
目前我一直在使用calendar.components.Day来检查两个日期是否具有相同的值,但它没有返回正确的答案:
func consecutiveDatesCheck(dateArray: [NSDate]) -> Int {
// The incoming parameter dateArray is immutable, so first make it mutable
var mutableArray = dateArray
// Next, sort the incoming array
mutableArray.sortInPlace({ $0.compare($1) == NSComparisonResult.OrderedAscending })
var x = 0
var numberOfConsecutiveDays = 1
var streakArray = [Int]()
var notSameDays = [NSDate]()
// Cycle through the array, comparing the x and x + 1 elements
while x + 1 < mutableArray.count {
let calendar: NSCalendar = NSCalendar.currentCalendar()
let components = calendar.components(.Day, fromDate: mutableArray[x], toDate: mutableArray[x + 1], options: [])
// If the difference between the dates is greater than 1, append the streak to streakArray and reset the counter
if abs(components.day) = 0 {
streakArray.append(numberOfConsecutiveDays)
numberOfConsecutiveDays = 1
}
// If the difference between the days is exactly 1, add one to the current streak
else if abs(components.day) == 1 {
numberOfConsecutiveDays += 1
}
x += 1
}
// Append the final streak to streakArray
streakArray.append(numberOfConsecutiveDays)
print(streakArray)
// Return the user's longest streak
return streakArray.maxElement()!
} /*
我在dateArray中的当前数据:
2016-08-20 06:38:23 +0000
2016-08-20 06:43:59 +0000
2016-08-20 06:49:19 +0000
2016-08-20 06:58:59 +0000
2016-08-20 07:05:44 +0000
2016-08-20 09:05:25 +0000
2016-09-02 12:05:55 +0000
2016-09-02 17:39:01 +0000
2016-09-03 13:37:31 +0000
2016-09-03 13:41:10 +0000
2016-09-03 13:59:36 +0000
2016-09-03 14:26:11 +0000
2016-09-03 14:48:57 +0000
2016-09-03 14:51:25 +0000
2016-09-03 15:06:56 +0000
2016-09-03 15:15:00 +0000
2016-09-04 13:53:48 +0000
2016-09-04 13:56:13 +0000
2016-09-04 14:16:29 +0000
2016-09-04 17:33:16 +0000
2016-09-05 16:53:32 +0000
2016-09-06 12:20:16 +0000
2016-09-06 15:19:14 +0000
2016-09-06 15:27:07 +0000
2016-09-06 15:30:48 +0000
2016-09-06 15:32:14 +0000
2016-09-06 15:39:34 +0000
2016-09-06 15:53:15 +0000
2016-09-06 16:08:45 +0000
2016-09-06 16:21:15 +0000
2016-09-06 17:41:09 +0000
2016-09-10 13:04:11 +0000
答案 0 :(得分:0)
编辑:我不是100%明确您的要求。我想你想要的是你有测量数据的当天结束的连续天数。更新了我的答案。
func consecutiveDatesCheck(dateArray: [NSDate]) -> Int {
let calendar = NSCalendar.currentCalendar()
let uniqueDates = NSSet(array: dateArray.map { calendar.startOfDayForDate($0) }).sort {
$0.timeIntervalSince1970 > $1.timeIntervalSince1970
} as! [NSDate]
var lastDate = calendar.startOfDayForDate(NSDate())
var i = 0
while i < uniqueDates.count && uniqueDates[i].compare(lastDate) == .OrderedSame {
lastDate = calendar.dateByAddingUnit(.Day, value: -1, toDate: lastDate, options: [])!
i += 1
}
return i
}