0

I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:

func sortDates(array:NSMutableArray)->[String]  {

        var strArray:[String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
        var convertedArray: [Date] = []
        for dat in array {
            let date = dateFormatter.date(from: dat as! String)
            convertedArray.append(date!)
        }
        let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
        for value in arrDates {
            let formatter = DateFormatter()
            // initially set the format based on your datepicker date
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: value)
            // convert your string to date
            let yourDate = formatter.date(from: myString)
            if yourDate != nil {
                //then again set the date format whhich type of output you need
                formatter.dateFormat = "yyyy-MM-dd"
                // again convert your date to string
                let myStringafd = formatter.string(from: yourDate!)
                strArray.append(myStringafd)
            }
        }
        return strArray
    }

Please guide me where I am doing wrong ?

3
  • 1
    What do you mean when you say "it is not happening"? Explain what your code is doing. I do not want to read through code to try to understand it. and determine what it is doing wrong. Commented Jun 6, 2017 at 8:26
  • 1
    Use yyyy-MM-dd, not with mm The lowercase one is for minutes (see the doc unicode.org/reports/tr35/tr35-31/…). Commented Jun 6, 2017 at 8:28
  • 1
    Apart from the identifier issue you can compare easier $0 < $1 Commented Jun 6, 2017 at 8:33

4 Answers 4

2

It is not necessary to convert these strings to Date type. You can simply sort them as strings and they will come out in the right order.

Sign up to request clarification or add additional context in comments.

Comments

1

You could create an extension to convert the string to date and then just append all your dates-objects to an array and sort that array.

Extensions:

extension String {
    var toDate: Date {
        return Date.Formatter.customDate.date(from: self)!
    }
}

extension Date {
    struct Formatter {
        static let customDate: DateFormatter = {
            let formatter = DateFormatter()
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.dateFormat = "yyyy-MM-dd"
            return formatter
        }()
    }
}

Usage:

let d1 = "2017-01-01".toDate
let d2 = "2016-01-01".toDate
let d3 = "2018-01-01".toDate
let d4 = "2013-01-01".toDate

let convertedArray = [d1,d2, d3, d4]
let sorted = convertedArray.sorted() // note that the sort works on a string too.
print(sorted)

Comments

0
extension String  {

func date(format: String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = format
    let date = dateFormatter.date(from: self)
    return date
}

}
extension Date {
func string(format: String) -> String {
    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = format
    return dateFormatterPrint.string(from: self) as String
}
}
var datesSting = ["2017-07-06","2017-08-07","2017-07-07"]

let soteddates  = datesSting.map { (obj) -> Date in
    return obj.date(format: "yyyy-MM-DD")!
}

let sorteedStings = soteddates.sorted { (obj1, obj2) -> Bool in
    return obj1.compare(obj2) == ComparisonResult.orderedAscending
}.map { (obj) -> String in
   return obj.string(format:  "yyyy-MM-DD")
}

print(sorteedStings)

Comments

0

Here is mine code:

   let arrCurrentDate = [“2017-07-06”, “2017-06-07", “2017-07-07”]
   var arrConverted: [Date] = []

   let dateFrmt = DateFormatter()
   dateFrmt.dateFormat = “yyyy-MM-dd”

   for dateCurrent in arrCurrentDate {
     let date = dateFrmt.date(from: dateCurrent)
     arrConverted.append(date!)
   }       
   arrConverted.sort(by: {$0.compare($1) == .orderedAscending})       
   arrConverted.sorted(by: {$0.timeIntervalSince1970 < $1.timeIntervalSince1970})

   print(arrConverted)

You can change your order also:

.orderedAscending .orderedSame .orderedDescending

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.