How to sort array of dates as string?

I have array of string. items are dates , such this

let array = ["2019-1-10","2015-4-2","2010-11-21"]

how to sort this Descending?

Accepted Reply

First of all, you should delete the duplicate question.


The title is a little bit confusing, but I guess you want to sort an Array of date String, with comparison as date.


One simple way is converting String to Date, for comparison:

let array = ["2019-1-10","2010-2-3","2015-4-2","2010-11-21"]
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
df.locale = Locale(identifier: "en_US_POSIX")
df.timeZone = TimeZone(identifier: "UTC")!

let sortedArray = array.sorted {df.date(from: $0)! > df.date(from: $1)!}
print(sortedArray) //->["2019-1-10", "2015-4-2", "2010-11-21", "2010-2-3"]


Another way, you may use numeric comparison available in Foundation.

let array = ["2019-1-10","2010-2-3","2015-4-2","2010-11-21"]

let sortedArray = array.sorted {$0.compare($1, options: .numeric) == .orderedDescending}
print(sortedArray) //->["2019-1-10", "2015-4-2", "2010-11-21", "2010-2-3"]


But, generally, date is sort of meta-info of some other things and it rarely happens that an Array of date String appears independently in actual apps. If you can provide more context about why you need to sort such an Array, you would get better responses.

Replies

You can use a regex to parse the strings and sort.


Something like (can certainly be simplified):

func parser(aDate: String) -> (y: Int, m: Int, d: Int) {
    var year = 0
    var month = 0
    var day = 0
   
    let patternY = "[0-9]{4}" // 1 or 2 digits, followed by -
    let regexY = try! NSRegularExpression(pattern: patternY)
    if let matchY = regexY.firstMatch(in: aDate, range: NSRange(0..<adate.utf16.count)) {<br="">        let yStr = String(aDate[Range(matchY.range(at: 0), in: aDate)!])
        year = Int(yStr) ?? 0
        let patternM = "[-][0-9]{1,2}"  //  1 or 2 digits
        let regexM = try! NSRegularExpression(pattern: patternM)
        if let matchM = regexM.firstMatch(in: aDate, range: NSRange(0..<adate.utf16.count)) {<br="">            let mStr = String(aDate[Range(matchM.range(at: 0), in: aDate)!]).dropFirst()
            month = Int(mStr) ?? 0
            let patternD = "[-][0-9]{1,2}"  //  1 or 2 digits
            let regexD = try! NSRegularExpression(pattern: patternD)
            if let matchD = regexD.firstMatch(in: aDate, range: NSRange(5..<adate.utf16.count)) { ="" start="" after="" the="" first="" -="" to="" skip="" it<br="">                let dStr = String(aDate[Range(matchD.range(at: 0), in: aDate)!]).dropFirst()
                day = Int(dStr) ?? 0
            }
        }
        return (year, month, day)
    } else {
        print("No match")
        return (0, 0, 0)
    }
}
parser(aDate: "2019-1-19")

let array = ["2019-1-10","2015-4-2","2010-11-21", "2016-11-22", "2019-4-3", "2015-5-3"]
let newArray = array.map() { parser(aDate: $0)}
let sorted = newArray.sorted(by: { ($0.y,$0.m,$0.d) >= ($1.y, $1.m, $1.d)})
let orderedArray = sorted.map() { String($0.y) + "-" + String($0.m) + "-" + String($0.d) }
print(orderedArray)

First of all, you should delete the duplicate question.


The title is a little bit confusing, but I guess you want to sort an Array of date String, with comparison as date.


One simple way is converting String to Date, for comparison:

let array = ["2019-1-10","2010-2-3","2015-4-2","2010-11-21"]
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
df.locale = Locale(identifier: "en_US_POSIX")
df.timeZone = TimeZone(identifier: "UTC")!

let sortedArray = array.sorted {df.date(from: $0)! > df.date(from: $1)!}
print(sortedArray) //->["2019-1-10", "2015-4-2", "2010-11-21", "2010-2-3"]


Another way, you may use numeric comparison available in Foundation.

let array = ["2019-1-10","2010-2-3","2015-4-2","2010-11-21"]

let sortedArray = array.sorted {$0.compare($1, options: .numeric) == .orderedDescending}
print(sortedArray) //->["2019-1-10", "2015-4-2", "2010-11-21", "2010-2-3"]


But, generally, date is sort of meta-info of some other things and it rarely happens that an Array of date String appears independently in actual apps. If you can provide more context about why you need to sort such an Array, you would get better responses.