使用String Formate

时间:2018-02-15 07:21:06

标签: ios arrays swift sorting date

我想用数据对数组中的数据进行排序。我在数组索引中使用键" 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"来排序数组中日期的升序。它提供了开始日期的字符串。请提供建议,使用日期

在数组内部进行排序

3 个答案:

答案 0 :(得分:3)

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

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)

答案 1 :(得分:3)

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中使用游乐场运行良好。

答案 2 :(得分:2)

使用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)