我正在通过编码来尝试在swift3中两个日期之间的日子。不幸的是,我收到错误并且运行失败。请告诉我如何解决以及如何在swift3中获取两个日期之间的日历日。
static func getDaysList(_ startDate:String, endDate:String, interval:Int) -> [Date] {
var dayRange = [Date]()
let inter = TimeInterval(interval * 60 * 60)
let ti:TimeInterval = inter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = datetimeformat
let dateTo = dateFormatter.date(from: endDate)
var nextDate = dateFormatter.date(from: startDate)
let endDate = dateTo!.addingTimeInterval(ti)
var startTime = NSDate()
while nextDate!.compare(endDate) == ComparisonResult.orderedAscending {
startTime = nextDate! as NSDate
dayRange.append(startTime as Date)
nextDate = nextDate!.addingTimeInterval(ti)
startTime = nextDate! as NSDate
}
return dayRange
}
致命错误:在解包可选值时意外发现nil
指向let endDate = dateTo!.addingTimeInterval(ti)
答案 0 :(得分:-1)
这里
let dateTo = dateFormatter.date(from: endDate)
您的endDate
可能是dateFormatter
格式不正确的字符串。因此dateTo
最终为nil
并崩溃:
let endDate = dateTo!.addingTimeInterval(ti)