按日期对数组中的对象进行排序 [英] Sort Objects in Array by date

查看:45
本文介绍了按日期对数组中的对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中包含一个名为 HistoryObject 的对象,它具有诸如日期"、名称"等属性.

I have an array containing an object called HistoryObject and it has properties such as "date", "name", etc.

我像这样对数组进行排序:

I am sorting the array like so:

 let sortedArray = HistoryArray.sort({ $0.date.compare($1.date) == NSComparisonResult.OrderedDescending})

应该将日期从新到旧排序.例如:

which is supposed to sort the date from newer to oldest. For example:

  • 2016 年 6 月 30 日
  • 2016 年 6 月 29 日

等等.

但是当我的数组包含Jul 2, 2016"时,排序后的数组变为:

But when my array contains "Jul 2, 2016" the sorted array becomes:

  • 2016 年 6 月 30 日
  • 2016 年 6 月 29 日
  • 2016 年 7 月 2 日

排序后Jul 2, 2016"应该在什么地方,现在它在底部?我该如何解决这个问题?

Where "Jul 2, 2016" should be on top after sorting, now it's on the bottom? How can I fix this problem?

推荐答案

使用 Swift 4 &斯威夫特 3

let testArray = ["25 Jun, 2016", "30 Jun, 2016", "28 Jun, 2016", "2 Jul, 2016"]
var convertedArray: [Date] = []

var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MM, yyyy"// yyyy-MM-dd"

for dat in testArray {
    let date = dateFormatter.date(from: dat)
    if let date = date {
        convertedArray.append(date)
    }
}

var ready = convertedArray.sorted(by: { $0.compare($1) == .orderedDescending })

print(ready)

使用 Swift 2

例如,您有一个带日期的数组和另一个 1 数组,您将在其中保存转换后的日期:

For example you have the array with dates and another 1 array, where you will save the converted dates:

var testArray = ["25 Jun, 2016", "30 Jun, 2016", "28 Jun, 2016", "2 Jul, 2016"]
var convertedArray: [NSDate] = []

之后我们转换日期:

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MM, yyyy"// yyyy-MM-dd"

for dat in testArray {
    var date = dateFormatter.dateFromString(dat)
    convertedArray.append(date!)
}

结果:

var ready = convertedArray.sort({ $0.compare($1) == .OrderedDescending })

print(ready)

这篇关于按日期对数组中的对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆