微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从一个字符串迅速拆分两个日期

如何解决从一个字符串迅速拆分两个日期

我有一个按钮,当用户按下它时,它将使用事件的开始日期和结束日期将事件的日期保存到他们的日历中。

此开始日期和结束日期是从json响应中加载的,但是两个日期都存储在一个字符串中。

我收到的响应格式如下:

{
   "events":[
      {
         "date":"5/12/2021 - 5/14/2021",},{
         "date":"6/22/2021 - 6/25/2021",}
       ]
}

为了正确保存到日历,我需要将开始日期和结束日期与以下格式的字符串分开:“ MM / DD / YYYY-MM / DD / YYYY”,以便字符串中的第一个日期为变量startDate,第二个日期是变量endDate。

我能够解析json响应,并且如果我对两个“虚拟”数组进行硬编码,则按钮可以正常工作,但是一旦收到此“ MM / DD / YYYY-MM / DD / YYYY”?

解决方法

这应该对您有用:

struct Response: Codable {
    let events: [Event]
}

struct Event: Codable {
    let date: String
    
    let startDate: Date
    let endDate: Date
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        date = try container.decode(String.self,forKey: .date)
        
        let splitted = date.components(separatedBy: " - ")
        
        guard let startDateString = splitted.first,let endDateString = splitted.last else {
            throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [],debugDescription: "'date' should follow the format 'DATE1 - DATE2'"))
        }
            
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "M/dd/yyyy"
            
        guard let extractedStartDate = formatter.date(from: startDateString),let extractedEndDate = formatter.date(from: endDateString) else {
            throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [],debugDescription: "The provided dates are not in the correct format M/dd/yyyy"))
        }
        startDate = extractedStartDate
        endDate = extractedEndDate
    }
}

还有一个从json解析它的示例:

let json = """
{
   "events":[
      {
         "date":"5/12/2021 - 5/14/2021",},{
         "date":"6/22/2021 - 6/25/2021",}
       ]
}
"""

let response = try JSONDecoder().decode(Response.self,from: json.data(using: .utf8)!)
print(response.events)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。