致命错误:索引超出范围而不使用任何数组

时间:2017-03-17 07:53:34

标签: ios nsdateformatter

致命错误:当我使用循环

将日期转换为工作日时,索引超出范围而不使用任何数组
 func getDayOfWeek(_ today:String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        let date = dateFormatter.date(from:today)
        let weekDay = dateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from:date!)]
        return weekDay
    }

3 个答案:

答案 0 :(得分:2)

Calendar.current.component(.weekday, from:date!)从1到7开始,但weekdaySymbols的索引仅从0到6,因此您必须减去1以获得正确的工作日:

let weekDay = dateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from:date!)-1]

同样应该使用if let和其他答案建议的可选项,以避免崩溃

答案 1 :(得分:0)

这是一个数组:

dateFormatter.weekdaySymbols

另外' date'如果字符串格式错误,则可能为零。你应该这样检查:

func getDayOfWeek(_ today:String) -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    if let date = dateFormatter.date(from:today) {
        let weekDay = dateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from:date)]
        return weekDay
    }
    return nil
}

答案 2 :(得分:0)

您可能需要将周日转换为周索引!

let weekname = getWeekDayName(weekDay: calendar.component(.weekday, from: date()))

func getWeekDayName(weekDay:Int) -> String
{
    let f = DateFormatter()
    let index:Int = (weekDay - 1) % 7
    print("Week No: " + String(weekNo) + " No: " + String(index))
    let weekName = f.weekdaySymbols[index]
    print("Week Name: " + weekName)
    return weekName
}