I have a array like
"11 Aug 2015",
"24 Sep 2014",
"25 Aug 2014",
"07 Aug 2014",
"07 Aug 2014"
i want to find maximum and minimum dates in it.
modifieddateArray.valueForKeyPath("@max.self")
modifieddateArray.valueForKeyPath("@min.self")
i used the above functions it gives the out like
max as 25 Aug 2014
min as 07 Aug 2014
but max date is 11 Aug 2015 and min as 07 Sept 2014
It considering on the first value greater as 25 and least as 07. How could i solve.
Thanks in advance
// Operator Overloading Methods
func >(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
// String to date
func dateFromString(dateStr: String) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd LLL yyyy"
// Eric D's suggestion, forcing locale to en_EN
dateFormatter.locale = NSLocale(localeIdentifier: "en_EN")
return dateFormatter.dateFromString(dateStr)!
}
// Date to String
func stringFromDate(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd LLL yyyy"
// Eric D's suggestion, forcing locale to en_EN
dateFormatter.locale = NSLocale(localeIdentifier: "en_EN")
return dateFormatter.stringFromDate(date)
}
// Array of String Dates
var dates = ["11 Aug 2015",
"24 Sep 2014",
"25 Aug 2014",
"07 Aug 2014",
"07 Aug 2014"]
// Map the Strings to NSDate
var dateInstances = dates.map({dateFromString($0)})
// Find Max
let maxVal = stringFromDate(dateInstances.reduce(dateInstances[0]){$0 > $1 ? $1 : $0})
// Find Min
let minVal = stringFromDate(dateInstances.reduce(dateInstances[0]){$0 < $1 ? $1 : $0})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With