【问题标题】:Sorting of an Array within with Date which comes in String Formate使用字符串格式的日期对数组进行排序
【发布时间】:2018-02-15 07:21:05
【问题描述】:

我想用日期对数组中的数据进行排序。我在数组索引中使用字符串格式的键“start_date”获取日期 我有以下数据数组:

    [
        {
         city = Ahmedabad;
        "start_date" = "2018-12-14";
        "start_time" = "09:00:00";
    },
        {
        city = Ahmedabad;
        "start_date" = "2018-12-13";
        "start_time" = "09:00:00";
    },
        {
         city = Ahmedabad;
        "start_date" = "2018-10-05";
        "start_time" = "09:00:00";
    },
        {
        city = Ahmedabad;
        "start_date" = "2018-10-03";
        "start_time" = "09:00:00";
    },
        {
        city = Ahmedabad;
        "start_date" = "2018-10-01";
        "start_time" = "09:00:00";
    },
        {
        city = Ahmedabad;
        "start_date" = "2018-09-04";
        "start_time" = "09:00:00";
    },
        {
        city = "Subang Jaya";
        "start_date" = "2018-10-15";
        "start_time" = "09:00:00";
    },
        {
        city = Kuching;
        "start_date" = "2018-08-22";
        "start_time" = "10:00:00";
    }
]

我想使用提供开始日期字符串的键“start_date”按数组内日期的升序排序。请为我提供使用日期在数组内进行排序的建议

【问题讨论】:

  • 你还没有日期,你有一个字符串。首先将您的字典 (JSON) 解析为对象。
  • @Sulthan 如何解析成对象?
  • @Sulthan 这是我使用 Alamofire 调用我的 web api 后的回应
  • 您如何拥有该数据的数组?使用命名元组?
  • 如果您想稍后使用其他标准对这些数据进行排序怎么办?你确定你不想像 Sulthan 所说的那样创建对象吗……然后将这些对象中的日期变量转换为 DateTime 的实例……然后让对象实现 然后你可以按照你想要的任何方式对它们进行排序。如果您接受,我会将这条评论转换为真正的答案!嘻嘻!!

标签: ios arrays swift sorting date


【解决方案1】:

在日期对象中转换您的日期和时间字符串,然后对数组进行排序。请检查以下代码

let array = [
            [
                "city" : "Ahmedabad",
                "start_date" : "2018-12-12",
                "start_time" : "09:00:00"
            ],
            [
                "city" : "Kuching",
                "start_date" : "2018-12-13",
                "start_time" : "09:00:00"
            ]
        ]

let dateFormater = DateFormatter()
//if you want sorting using start_date and start_time
dateFormater.dateFormat = "yyyy-MM-dd hh:mm:ss"
//else (sort only with start_date)
dateFormater.dateFormat = "yyyy-MM-dd"

let sortedArray = array.sorted { (dictionary1, dictionary2) -> Bool in
    //if you want sorting using start_date and start_time
    let date1 = dictionary1["start_date"]!+" "+dictionary1["start_time"]!
    let date2 = dictionary2["start_date"]!+" "+dictionary2["start_time"]!
    //else (sort only with start_date)
    let date1 = dictionary1["start_date"]!
    let date2 = dictionary2["start_date"]!

    let d1 = dateFormater.date(from: date1)!
    let d2 = dateFormater.date(from: date2)!
    return d1 < d2
}

print(sortedArray)

【讨论】:

    【解决方案2】:

    Swift 4 解决方案:

    首先创建一个与 JSON 对象重叠的 Codable 结构。

    import Foundation
    
    struct City: Codable {
        let city: String
        let start_date: Date
        let start_time: String
    }
    

    我假设呈现的数据是 JSON 结构。所以它的多行表示看起来像这样:

    let jsonString = """
    [
        {
            "city": "Ahmedabad",
            "start_date": "2018-12-14",
            "start_time": "09:00:00"
        },
        {
            "city": "Ahmedabad",
            "start_date": "2018-12-13",
            "start_time": "09:00:00"
        },
        {
            "city": "Ahmedabad",
            "start_date": "2018-10-05",
            "start_time": "09:00:00"
        },
        {
            "city": "Ahmedabad",
            "start_date": "2018-10-03",
            "start_time": "09:00:00"
        },
        {
            "city": "Ahmedabad",
            "start_date": "2018-10-01",
            "start_time": "09:00:00"
        },
        {
            "city": "Ahmedabad",
            "start_date": "2018-09-04",
            "start_time": "09:00:00"
        },
        {
            "city": "Subang Jaya",
            "start_date": "2018-10-15",
            "start_time": "09:00:00"
        },
        {
            "city": "Ahmedabad",
            "start_date": "2018-08-22",
            "start_time": "10:00:00"
        }
    ]
    """
    

    然后进行排序:

    // Create a DateFormatter to conform to the dateformat in the JSON structure.
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    
    // Get Data from the jsonString and then setup a JSONDecoder to work with it, dont
    // forget the dateDecodingStrategy.
    
    let jsonData = jsonString.data(using: .utf8)!
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .formatted(dateFormatter)
    
    // Get all the cities with their dates (and times).
    
    let cities = try! decoder.decode([City].self, from: jsonData)
    
    // Because the Codeable interface and the DateFormatter we can now really easy sort on the dates
    // resulting in:
    
    cities.sorted { (first, second) -> Bool in
        return first.start_date < second.start_date
    }
    

    此代码使用 Xcode 9 中的 Playground 运行良好。

    【讨论】:

      【解决方案3】:

      Swift 4 解决方案

      首先,您需要将响应解析为您的自定义类型。为此,您应该有一个 structclass 什么的。我打算用structure:

      // Decodable protocol is used so that your response data can be deserialized into a Type
      struct Root: Decodable {
          let city: String
          let startDate: String
          let startTime: String
      
          private enum CodingKeys: String, CodingKey {
              case city
              case startDate = "start_date"
              case startTime = "start_time"
          }
      }
      extension Root {
          /// converts the startDate to an actual date type which will be used for comparison
          var convertedStartDate: Date {
              return dateFormatter.date(from: startDate) ?? Date() // if server data has something in start_date that can't be converted to any date, assume that refers to current date. Or you can have your own logic here
          }
          private var dateFormatter: DateFormatter {
              let dateFormatter = DateFormatter()
              dateFormatter.dateFormat = "yyyy-MM-dd"
              return dateFormatter
          }
      }
      

      示例数据: (最终,您将从您的回复中获得此数据)

      let jsonData = """
      [
      {
      "city" : "Ahmedabad",
      "start_date" : "2018-12-14",
      "start_time" : "09:00:00",
      },
      {
      "city" : "Ahmedabad",
      "start_date" : "2018-12-13",
      "start_time" : "09:00:00",
      },
      {
      "city" : "Ahmedabad",
      "start_date" : "2018-10-05",
      "start_time" : "09:00:00",
      },
      {
      "city" : "Ahmedabad",
      "start_date" : "2018-10-03",
      "start_time" : "09:00:00",
      },
      {
      "city" : "Ahmedabad",
      "start_date" : "2018-10-01",
      "start_time" : "09:00:00",
      },
      {
      "city" : "Ahmedabad",
      "start_date" : "2018-09-04",
      "start_time" : "09:00:00",
      },
      {
      "city" : "Subang Jaya",
      "start_date" : "2018-10-15",
      "start_time" : "09:00:00",
      },
      {
      "city" : "Kuching",
      "start_date" : "2018-08-22",
      "start_time" : "10:00:00",
      }
      ]
      """.data(using: .utf8)!
      

      然后:将您的数据反序列化为您的自定义类型

      var array = [Root]()
      do {
          let root = try JSONDecoder().decode([Root].self, from: jsonData)
          array = root
      } catch {
          print(error)
      }
      
      // now you can sort your data easily
      let sortedArray = array.sorted { $0.convertedStartDate < $1.convertedStartDate }
      print(sortedArray)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-21
        • 2021-07-13
        • 2021-07-30
        • 2021-03-08
        • 2019-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多