在Swift中按天分组约会

时间:2016-12-20 10:17:31

标签: ios arrays swift

我有一组日期字符串(见下文)。我想将此数组用于我的表视图,以显示按天分类的时间(类似于iOS联系人应用中的联系人表,按字母分类)。

作为第一步,我想将日期字符串数组分组以实现一系列分类约会时间(见下文),请告知我如何实现这一目标?我看了很多例子,但确实在堆栈溢出时找到了类似的例子。

这是我的输入

let dateStrings = [
"2016-12-20 16:00:00", 
"2016-12-20 16:15:00", 
"2016-12-21 16:00:00", 
"2016-12-22 16:00:00", 
"2016-12-22 16:15:00", 
"2016-12-22 16:30:00"
]

我想要的输出

let categorisedAppointmentTimes = [ 
["Tue, 20 Dec" : ["4:00 pm", "4:15 pm"]],
["Wed, 21 Dec" : ["4:00 pm"]],
["Thu, 22 Dec" : ["4:00 pm", "4:15 pm", "4:30 pm"]]
]

2 个答案:

答案 0 :(得分:1)

您需要使用DateFormatter来解析StringDate以及DateString

请阅读此内容以更好地了解这些运营商。 http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/

    var categorisedAppointmentTimes : [String : [String]] = [:]

    let dateStrings = [
        "2016-12-20 16:00:00",
        "2016-12-20 16:15:00",
        "2016-12-21 16:00:00",
        "2016-12-22 16:00:00", 
        "2016-12-22 16:15:00", 
        "2016-12-22 16:30:00"
    ]


    let inputDateFormatter = DateFormatter()
    inputDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

    let keyDateFormatter = DateFormatter()
    keyDateFormatter.dateFormat = "EEE, dd MMM"

    let valueDateFormatter = DateFormatter()
    valueDateFormatter.dateFormat = "h:mm a"


    for dateString in dateStrings {
        let date = inputDateFormatter.date(from: dateString)

        let dateKey = keyDateFormatter.string(from: date!)

        let dateValue = valueDateFormatter.string(from: date!)

        if categorisedAppointmentTimes.index(forKey: dateKey) != nil {
            categorisedAppointmentTimes[dateKey]!.append(dateValue)
        }else{
            categorisedAppointmentTimes[dateKey] = [dateValue]
        }
    }

    print(categorisedAppointmentTimes)

    //["Tue, 20 Dec": ["4:00 PM", "4:15 PM"],
    // "Thu, 22 Dec": ["4:00 PM", "4:15 PM", "4:30 PM"],
    // "Wed, 21 Dec": ["4:00 PM"]]

答案 1 :(得分:0)

我认为这会达到您想要的效果,但这种情况非常具体,您必须确保dateStrings始终采用您共享的格式。 "约会时间"

 var categorisedAppointmentTimes : [String : [String]] = [:]
    let dateStrings = [
        "2016-12-20 16:00:00",
        "2016-12-20 16:15:00",
        "2016-12-21 16:00:00",
        "2016-12-22 16:00:00",
        "2016-12-22 16:15:00",
        "2016-12-22 16:30:00"
    ]
    dateStrings.sorted { (s1, s2) -> Bool in
        s1 > s2
    }
    for date in dateStrings {
        let stringComponets = date.components(separatedBy: " ")
        guard let _ = categorisedAppointmentTimes[stringComponets[0]] else {
            categorisedAppointmentTimes[stringComponets[0]]  = [stringComponets[1]]
            continue
        }
        categorisedAppointmentTimes[stringComponets[0]]?.append(contentsOf: [stringComponets[1]])

    }