如何按月份对获取的日期进行分组 [英] How can I group fetched dates by Month
问题描述
我以日期类型将数据插入了核心数据,但是当我尝试从数据库中获取数据时,无法按月对它们进行分组。您可以找到我尝试的解决方案的代码,但是没有用。
I inserted data into core-data with a type of Date but when I try to fetch data's from the database I couldn't group them by month. You can find the code that I tried for a solution but it didn't work.
let groupedDict = Dictionary(grouping: self.lessons) { (month) -> Date in
return month.lessonDate!
}
var groupedMonth = [[Lessons]]()
let keys = groupedDict.keys.sorted()
keys.forEach { (key) in
groupedMonth.append(groupedDict[key]!)
}
groupedMonth.forEach ({
$0.forEach({print($0)})
print("--------")
})
如果我给你一个例子,想要完成。例如:
If I should give you an example of what I want to accomplish. Here is the example:
采样日期:
-
04.07。 2017
04.07.2017
01.08.2018
01.08.2018
2018.08.2018
02.08.2018
05.08.2018
05.08.2018
19.09.2018
19.09.2018
07.09.2018
07.09.2018
我想对这些数据进行分组,例如
I wanted to group these data like
- 2017年6月
- 2018年8月
- 2018年9月
感谢您的帮助
推荐答案
您必须使用 Dictionary(grouping:by:)
有所不同。您必须返回要分组的值,而不是每节课都返回不同的组。
You have to use Dictionary(grouping:by:)
differently. You have to return the value you want to group by, not for every lesson a different group.
struct Lesson {
let lessonDate: Date
}
extension Date {
func addDays(_ days: Int) -> Date {
return Calendar.current.date(byAdding: .day, value: days, to: self)!
}
func addMonths(_ months: Int) -> Date {
return Calendar.current.date(byAdding: .month, value: months, to: self)!
}
var month: Date {
let calendar = Calendar.current
return calendar.date(from: calendar.dateComponents([.month, .year], from: self))!
}
var prettyMonth: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
formatter.locale = Calendar.current.locale!
return formatter.string(from: self)
}
var prettyDate: String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
formatter.locale = Calendar.current.locale!
return formatter.string(from: self)
}
}
示例
Example
func testing() {
let lessons: [Lesson] = [
.init(lessonDate: Date().addDays(2)),
.init(lessonDate: Date().addDays(3)),
.init(lessonDate: Date().addMonths(1).addDays(1)),
.init(lessonDate: Date().addMonths(1).addDays(2)),
.init(lessonDate: Date().addMonths(1).addDays(3)),
.init(lessonDate: Date().addMonths(3)),
]
let groupedDict = Dictionary(grouping: lessons, by: { $0.lessonDate.month })
groupedDict
.sorted(by: { a, b in a.key < b.key })
.forEach {
print("----- \($0.key.prettyMonth) -----")
$0.value.forEach {
print("\($0.lessonDate.prettyDate)")
}
}
}
Produces
----- August 2018 -----
29. Aug 2018 at 19:38:13
30. Aug 2018 at 19:38:13
----- September 2018 -----
28. Sep 2018 at 19:38:13
29. Sep 2018 at 19:38:13
30. Sep 2018 at 19:38:13
----- November 2018 -----
27. Nov 2018 at 19:38:13
这篇关于如何按月份对获取的日期进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!