在数组中查找最大和最小日期

时间:2015-08-21 11:09:30

标签: ios swift nsdate

我有一个类似

的数组
    "11 Aug 2015",
    "24 Sep 2014",
    "25 Aug 2014",
    "07 Aug 2014",
    "07 Aug 2014"

我想在其中找到最大和最小日期。

modifieddateArray.valueForKeyPath("@max.self")
modifieddateArray.valueForKeyPath("@min.self")

我使用上面提到的功能

  

最高为2014年8月25日

     

min为2014年8月7日

但最长日期为2015年8月11日,最低日期为2014年9月7日

考虑第一个值大于25,最小值为07.我怎么能解决。

提前致谢

3 个答案:

答案 0 :(得分:6)

使用Swift强大的内置功能:

// 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})

游乐场输出:

Playground Output

答案 1 :(得分:0)

绝对不是最有效的方法,但非常简单并且有一些有趣的编码:

var dates = ["11 Aug 2015",
            "24 Sep 2014",
            "25 Aug 2014",
            "07 Aug 2014",
            "07 Aug 2014"]

        var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        var monthsNum = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]


        func convertToInt (date : String) -> Int {

            var arr = split(date) {$0 == " "}

            var c = 1
            for month in months {
                if (arr[1] == month) {
                    if (c < 10) {
                        return (arr[2]+"0"+String(c)+arr[0]).toInt()!
                    }
                    else {
                        return (arr[2]+String(c)+arr[0]).toInt()!
                    }

                }
                c++
            }

            return 0
        }

        func convertToString (date : Int) -> String {

            var dateString = String(date) as NSString

            var year = dateString.substringWithRange(NSRange(location: 0, length: 4))
            var month = dateString.substringWithRange(NSRange(location: 4, length: 2))
            var day = dateString.substringWithRange(NSRange(location: 6, length: 2))

            var c = 0
            for curMonth in monthsNum {

                if (curMonth == month) {
                    return year+" "+months[c]+" "+day
                }
                c++
            }


            return ""

        }

        var newDates = [Int]()

        for date in dates {
            newDates.append(convertToInt(date))
        }


        println(convertToString(maxElement(newDates)))
        println(convertToString(minElement(newDates)))

答案 2 :(得分:0)

我这样做了

 var itemsArray ["24 Aug 2014","29 Jul 1990","06 Jan 2050","18 OCT 2014","24 Aug 2019"]


    for item in modifieddateArray {
        var maxDate2 : NSDate = dateFormatter.dateFromString(item as! String)! //as! NSDate
        var value : Int = Int(NSDate().timeIntervalSinceDate(maxDate2))
        itemsArray.addObject(value)
    }
    //println(itemsArray)

    var minDateNum: AnyObject! = itemsArray.valueForKeyPath("@max.self")
    var maxDateNum: AnyObject! = itemsArray.valueForKeyPath("@min.self")
    //println("\(maxDate, minDate)")

    var indexMax = itemsArray.indexOfObject(maxDateNum!)
    var indexMIn = itemsArray.indexOfObject(minDateNum!)

    //println("\(indexMax, indexMIn)")

    maxDate = modifieddateArray.objectAtIndex(indexMax)
    minDate = modifieddateArray.objectAtIndex(indexMIn)
    //println("\(maxDate, minDate)")

计算时间间隔并找到最大值作为最小日期,最小值作为最大日期