【发布时间】:2021-12-18 15:29:45
【问题描述】:
[编辑] 在我的 fetchData 函数末尾添加这个就可以了:
//Sort the tableView by date and time if it's the same date
self.tasks.sort { if $0.date != $1.date {
return $0.date < $1.date
}
else {
return $0.hour < $1.hour
}
}
我刚开始编程,但我卡住了,基本上我有一个显示多个任务的表格视图,我想按日期对任务进行排序,所以我提取了任务的时间/小时(已经在 firebase 中创建)然后转换将它们转换为 Date 以对它们进行排序,但我不知道如何将它们“转换”回字符串以将它们放回我的 cell.date.text ... 这就是我到目前为止尝试的原因:
var convertedArray: [Date] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! MyTasksTableCell
//Gathering the date and hour (string)
let date = "\(Tasks[indexPath.row].date)"
let hour = "\(Tasks[indexPath.row].hour)"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy 'at' HH:mm"
let DateHour = date + " at " + hour
//OUTPUT:
// 10/22/2021 at 15:10
// 10/21/2021 at 22:24
// 10/21/2021 at 01:55
// 12/16/2021 at 14:50
// Converting them to a Date
let finalDate = dateFormatter.date(from: DateHour)
//OUTPUT:
// Optional(2021-12-16 13:50:00 +0000)
// Optional(2021-10-22 13:10:00 +0000)
// Optional(2021-10-21 20:24:00 +0000)
// Optional(2021-10-20 23:55:00 +0000)
//Sorting them
convertedArray.append(finalDate!)
let dateObject = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
//OUTPUT:
// [2021-10-22 13:10:00 +0000]
// [2021-10-22 13:10:00 +0000, 2021-12-16 13:50:00 +0000]
// [2021-10-21 20:24:00 +0000, 2021-10-22 13:10:00 +0000, 2021-12-16 13:50:00 +0000]
// [2021-10-20 23:55:00 +0000, 2021-10-21 20:24:00 +0000, 2021-10-22 13:10:00 +0000, 2021-12-16 13:50:00 +0000]
for date in dateObject {
let date = dateFormatter.string(from: date)
//OUTPUT:
// 12/16/2021 at 14:50
// 10/22/2021 at 15:10
// 12/16/2021 at 14:50
// 10/21/2021 at 01:55
// 10/22/2021 at 15:10
// 12/16/2021 at 14:50
// 10/21/2021 at 01:55
// 10/21/2021 at 22:24
// 10/22/2021 at 15:10
// 12/16/2021 at 14:50
}
var newList = [String]()
for date in dateObject {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "MM/dd/yyyy 'at' HH:mm"
let convertDate = dateformatter.string(from: date)
newList.append(convertDate)
}
print(newList)
//OUTPUT:
// ["12/16/2021 at 14:50"]
// ["10/22/2021 at 15:10", "12/16/2021 at 14:50"]
// ["10/21/2021 at 22:24", "10/22/2021 at 15:10", "12/16/2021 at 14:50"]
// ["10/21/2021 at 01:55", "10/21/2021 at 22:24", "10/22/2021 at 15:10", "12/16/2021 at 14:50"]
【问题讨论】:
-
基本上从不修改数据源或在
cellForRow中进行大量计算。获取数据后立即将数据转换为所需的格式。 -
好的,我会试试的,谢谢!
标签: swift string sorting date tableview