1

I have an array of object with dateString(of creation) as parametere. I wanna sort the array of objects based on timestamp(of creation).

For example,

array = ["dateString":"2018-03-06", "dateString":"2018-03-05"]
Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
j.krissa
  • 223
  • 5
  • 21

3 Answers3

2

You can convert date string to date formate then compare with each to find sorted array.

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

var convertedArray: [Date] = []

var dateArray = ["2018-03-06", "2018-03-05"]
for dat in dateArray {
    let date = dateFormatter.date(from: dat)
    if let date = date {
        convertedArray.append(date)
    }
}

let ready = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
// For Descending use .orderedDescending 
print(ready) //[2018-05-02 18:30:00 +0000, 2018-06-02 18:30:00 +0000]

var newList = [String]()
for date in ready {
    let dateformatter =  DateFormatter()
    dateformatter.dateFormat = "dd-MM-yyyy"
    let convertDate = dateformatter.string(from: date)
    newList.append(convertDate)
}
print(newList) //["03-05-2018", "03-06-2018"] 
Sid Mhatre
  • 3,272
  • 1
  • 19
  • 38
1

Considering your array has the following format:

let array: [[String: String]] = [
    ["dateString":"2018-03-06"],
    ["dateString":"2018-03-05"]
]

You should use sorted method to get what you need:

let sortedArray = array.sorted { (obj1, obj2) -> Bool in
    if let date1 = obj1["dateString"], let date2 = obj2["dateString"] {
        return date1 < date2
    }
    return false
}
adriencog
  • 386
  • 1
  • 5
1

Assuming you are given an array of strings representing dates:

let array: [String] = ["2018-03-06", "2018-03-05"]

// Transform the given array of strings into an array of Date objects
var dates: [Date] = []
for dateString in array {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    if let date = dateFormatter.date(from: dateString) {
        dates.append(date)
    }
}
// Now apply any kind of sort you like
// e.g. ascending
dates.sort(by: { lhs, rhs in
    return lhs < rhs
})
// or descending
dates.sort(by: { lhs, rhs in
    return lhs > rhs
})
Vadim Popov
  • 1,177
  • 8
  • 17
  • With the given string format the conversion to `Date` is not necessary. Declare array as `var` and write `array.sort()` for the default ascending order. – vadian Mar 09 '18 at 12:50
  • @vadian the format could be any other. This method is applicable to any by changing `dateFormat` pattern – Vadim Popov Mar 09 '18 at 12:59