ios - 如何对字符串的日期进行排序?

标签 ios arrays swift sorting

我有一组日期为 2017-07-06,2017-06-07,2017-07-07。我想按升序对这些日期进行排序。所以 2017-06-07 将排在第一位。但这根本没有发生。我为此使用以下代码:

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
    }

请指导我哪里做错了?

最佳答案

不需要将这些字符串转换为日期类型。您只需将它们作为字符串进行排序,它们就会以正确的顺序出现。

关于ios - 如何对字符串的日期进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44384930/

相关文章:

ios - 将 UISegmentedControl 添加到 UISearchBar 而不是范围按钮

ios - LNPopupController 和 Tableviewcell 滑动

ios - 如何使用 begin-endUpdates() 和多个自定义单元格展开/折叠 UITableViewCells?

c - 将文本文件输入到c中的二维数组中

ios - 打开 URL 前播放声音

ios - 如何在 AVPlayerViewController 中播放视频时快速检测触摸

ios - 无法将类型 'MyClass' 的值分配给类型 'MFMailComposeViewControllerDelegate!' 的值

ios - 不从 JSON 调用中获取数据

c - 数组地址操作

Android动态数组ListPreference