在 swift 中,转换日期格式失败,但无法使用 ISO8601DateFormatter

In swift, failing converting date format, but cannot use ISO8601DateFormatter

我无法获得 'start' 值,测试了许多变体和格式化程序。出于生产原因,不能使用 ISO8601DateFormatter。

此代码是在日历上创建约会的一部分,因此我需要作为约会的开始 date/hour 开始。

最重要的是,我需要理解为什么在我尝试转换日期后这最后一行代码失败:

event.startDate 是我的 'start' 但无法设置它,因为转换日期失败

   guard let url = URL(string: "calshow:\(event.startDate.timeIntervalSinceReferenceDate)") else { return }
            DispatchQueue.main.async {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
      

我的代码:

date0

是我从 API 获得的日期,值为 2021-07-28 00:00:00 +0000

我在日历上创建事件的更新代码

let dateFormatter: DateFormatter = DateFormatter()

            dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
            let date = dateFormatter.string(from: date0)
            
            
            if let startTime = hours.from,
               let startDate = date.concats(startTime),
               let start = self.shortTimeFormatter.date(from: startDate) {
                event.startDate = start
                event.addAlarm(EKAlarm(absoluteDate: start.dayBefore))
                event.addAlarm(EKAlarm(absoluteDate: start.halfHourBefore))
                event.endDate = start.hourAfter
            }
            
            if let endTime = hours.to,
               let endDate = date.concats(endTime),
               let end = self.shortTimeFormatter.date(from: endDate) {
                event.endDate = end
            }

连接代码

  func concats(_ string: String, withSeparator separator: String? = "") -> String? {
        return [self, string].compactMap{ [=13=] }.joined(separator: separator! + " ")
    }

ShortDateTimeFormatter

public class ShortDateTimeFormatter: DateFormatter {
    
    override public init() {
        super.init()
        self.dateFormat = "dd/MM/yyyy HH:mm"
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

如果我理解代码,你会得到一个没有时间部分的 Date,你想以字符串格式添加时间 "HH:mm:ss"

Calendar 可以做到。您不需要将 Date 转换为 String 并返回 Date

首先创建一个将时间字符串转换为 Int 分量的函数

func timeComponents(from string: String) -> (Int, Int, Int)? {
    let comps = string.components(separatedBy: ":")
    guard comps.count == 3,
          let hr = Int(comps[0]),
          let mn = Int(comps[1]),
          let sc = Int(comps[2])
          else { return nil }
    return (hr, mn, sc)
}

然后用date(bySettingHour:minute:second:of:)

将时间加到date0
if let (hr, mn, sc) = timeComponents(from: "08:30:00") {
    let startDate = Calendar.current.date(bySettingHour: hr, minute: mn, second: sc, of: date0)
}

或者用DateComponents

func timeComponents(from string: String) -> DateComponents? {
    let comps = string.components(separatedBy: ":")
    guard comps.count == 3,
          let hr = Int(comps[0]),
          let mn = Int(comps[1]),
          let sc = Int(comps[2])
          else { return nil }
    return DateComponents(hour: hr, minute: mn, second: sc)
}

if let components = timeComponents(from: "08:30:00") {
    let startDate = Calendar.current.date(byAdding: components, to: date0, wrappingComponents: false)
}