A quick example on ISO8601DateFormatter and sorted(by:) function

Thomas Mak wrote at 2018-10-14.

#ios #swift

Here is an example of using ISO8601DateFormatter and sorted(by:) in Swift and iOS.

ISO 8601 is the YYYY-MM-DD format to represent date. In ISO8601DateFormatter, Swift expects the time as well: YYYY-MM-DDTHH:MM:SSZ. If we simply need the date without the time, we can set the .withFullDate format option.

let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = .withFullDate
let date = dateFormatter.date(from: "2018-10-11")

Also, within an array of instances, we can sort them by a date type instant variable by using the sorted(by:) function.

For example:

let students:[Student] = [
    Student(enrolledAt: "2018-02-02"),
    Student(enrolledAt: "2017-01-01"),
    Student(enrolledAt: "2017-12-31")
]

students.sorted(by: {$0.enrolledAt > $1.enrolledAt})

Here is a full runnable example:

import Foundation

class Student {
    var enrolledAt = Date()

    init(enrolledAt:String) {
        let dateFormatter = ISO8601DateFormatter()
        dateFormatter.formatOptions = .withFullDate
        self.enrolledAt = dateFormatter.date(from: enrolledAt)!
    }
    init() {
        self.enrolledAt = Date()
    }
}

let students:[Student] = [
    Student(),
    Student(enrolledAt: "2018-02-02"),
    Student(enrolledAt: "2017-01-01"),
    Student(enrolledAt: "2017-12-31")
]

students.sorted(by: {$0.enrolledAt > $1.enrolledAt})

students.sorted(by: {$0.enrolledAt < $1.enrolledAt})

Comments

no comments yet.

Please login to chat.