Last active
June 23, 2016 10:00
-
-
Save mlabraca/41ad4ef0c056fa16bd164602f8fbafdf to your computer and use it in GitHub Desktop.
Shows how to sort array of dates ascending and descending. As a extra, is supplied an NSDate extension to init NSDate from string with format yyyy/MM/dd HH:mm.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension NSDate { | |
convenience init(fromString: String) { | |
let formatter = NSDateFormatter() | |
formatter.dateFormat = "yyyy/MM/dd HH:mm" | |
formatter.timeZone = NSTimeZone(name: "GMT") | |
let date = formatter.dateFromString(fromString) ?? NSDate() | |
self.init(timeInterval:0, sinceDate:date) | |
} | |
} | |
let date1 = NSDate(fromString: "2015/10/25 18:00") | |
let date2 = NSDate(fromString: "2015/10/26 18:31") | |
let date3 = NSDate(fromString: "2015/10/26 17:15") | |
let date4 = NSDate(fromString: "2015/10/26 14:45") | |
let arrayDates = [date1, date2, date3, date4] | |
arrayDates.forEach { print($0)} | |
//output: | |
//2015-10-25 18:00:00 +0000 | |
//2015-10-26 18:31:00 +0000 | |
//2015-10-26 17:15:00 +0000 | |
//2015-10-26 14:45:00 +0000 | |
arrayDates.sort { $0.compare($1) == NSComparisonResult.OrderedDescending }.forEach { print($0) } | |
//output: | |
//2015-10-26 18:31:00 +0000 | |
//2015-10-26 17:15:00 +0000 | |
//2015-10-26 14:45:00 +0000 | |
//2015-10-25 18:00:00 +0000 | |
arrayDates.sort { $0.compare($1) == NSComparisonResult.OrderedAscending }.forEach { print($0) } | |
//output: | |
//2015-10-25 18:00:00 +0000 | |
//2015-10-26 14:45:00 +0000 | |
//2015-10-26 17:15:00 +0000 | |
//2015-10-26 18:31:00 +0000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment