我正在尝试计算一个人一天喝一杯水的时间(以一小时为间隔)的次数,我无法弄清楚如何正确构建这种数据结构,预期的数据将会看起来像这样:
day1 = [hour interval: [time, time, time], hour interval: [time], hour interval: [time], hour:[time]]
它会打印一个空数组...到目前为止,我有这个:
var counts = [String:Array<NSDate>]()
var dict = [[NSDate:Array<[String:Array<NSDate>]>]]()
//datesArray -> is an array of dates from something like monday to friday
/*
datesArray:
2016-07-23
2016-07-24
2016-07-25
2016-07-26
2016-07-27
2016-07-28
2016-07-29
2016-07-30
*/
for date in datesArray {
//tempDoses has the times when the user took the glass of water
/*
tempDoses:
2016-07-28 23:50:50 +0000
2016-07-26 13:06:57 +0000
2016-07-25 08:47:52 +0000
2016-07-25 08:46:47 +0000
2016-07-25 08:46:06 +0000
2016-07-24 23:25:07 +0000
2016-07-24 14:18:11 +0000
2016-07-24 13:58:35 +0000
2016-07-22 09:10:59 +0000
2016-07-22 09:10:26 +0000
2016-07-22 09:09:28 +0000
*/
for temp in tempDoses {
if calendar.isDate(date, inSameDayAsDate: temp.logTime)
let dateformatter = NSDateFormatter()
dateformatter.dateFormat = "HH:mm"
let myDate = dateformatter.stringFromDate(temp.logTime)
let h = self.getHour(myDate)
for m in counts {
var o = m
if o.0 == h {
o.1.append(temp.logTime)
}
}
}
}
if counts.count > 0 {
dict.append([date:[counts]])
counts.removeAll()
}else{
dict.append([date:[]])
}
}
预期结果:
2016-07-21 = []
2016-07-22 = ["10": [09:10, 09:13]]
2016-07-23 = []
2016-07-24 = ["15": [14:18], "14": [13:12, 13:56]]
2016-07-25 = ["09": [08:33, 08:40], "00": [23:10]]
2016-07-26 = ["14": [13:33]]
2016-07-27 = []
2016-07-28 = []
答案 0 :(得分:1)
您的预期输出与您的输入不符!例如,在2016-07-22
上:
// Input
2016-07-22 09:10:59 +0000
2016-07-22 09:10:26 +0000
2016-07-22 09:09:28 +0000
// My expected output
2016-07-22 = [9: ["09:10", "09:09"]]
// Your expected output:
2016-07-22 = ["10": [09:10, 09:13]]
使用下面的代码,直到获得所需内容。 特别注意时区,因为它是处理NSDate
时的主要错误来源:
let timeZone = NSTimeZone(forSecondsFromGMT: 0)
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = timeZone
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
formatter.timeZone = timeZone
var dict = [NSDate : [Int: [String]]]()
for date in datesArray {
let dailyDoses = doses
.filter { calendar.startOfDayForDate($0.logTime) == date }
.sort { $0.logTime.timeIntervalSince1970 < $1.logTime.timeIntervalSince1970 }
dict[date] = [Int: [String]]()
dailyDoses.forEach {
let hour = calendar.component(.Hour, fromDate: $0.logTime)
let str = formatter.stringFromDate($0.logTime)
if dict[date]![hour] == nil {
dict[date]![hour] = [String]()
}
if !(dict[date]![hour]!.contains { $0 == str }) {
dict[date]![hour]!.append(str)
}
}
}
// Print the result
for date in datesArray {
print(date, "=", dict[date]!)
}
/* Output:
2016-07-22 00:00:00 +0000 = [9: ["09:09", "09:10"]]
2016-07-23 00:00:00 +0000 = [:]
2016-07-24 00:00:00 +0000 = [14: ["14:18"], 23: ["23:25"], 13: ["13:58"]]
2016-07-25 00:00:00 +0000 = [8: ["08:46", "08:47"]]
2016-07-26 00:00:00 +0000 = [13: ["13:06"]]
2016-07-27 00:00:00 +0000 = [:]
2016-07-28 00:00:00 +0000 = [23: ["23:50"]]
*/