0

我在检查日期时崩溃了:

func cehckForDate(date: String?) -> Int{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
    let fromDt = dateFormatter.date(from: date ?? "")
    let curreentDate = Date()
    let order = Calendar.current.compare(curreentDate , to: fromDt!, toGranularity: .day)
    switch order {
    case .orderedAscending:
        return(2)
    case .orderedDescending:
        return(1)
    case .orderedSame:
        return(0)
    }
    return 0
}

我的崩溃在这里:

let order = Calendar.current.compare(curreentDate , to: fromDt!, toGranularity: .day)

我正在nilfromDt

我的约会对象是 2018-08-16 15:04:17

4

2 回答 2

1

就像@rmaddy 所说,问题在于您的日期格式和您的输入- 它们不匹配hh-> 12 小时格式,HH-> 24 小时格式,这是您所需要的。(请参阅底部的链接以检查您需要用于输入的内容)

func checkForDate(date: String = "") -> Int{
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    guard let validDateFound = dateFormatter.date(from: date) else {
        print("Invalid date received. Please check if the date matches the date format - \(date)")
        return -1 //Proper error code for invalid date
    }
    let order = Calendar.current.compare(Date() , to: validDateFound, toGranularity: .day)
    switch order {
    case .orderedAscending:
        return(2)
    case .orderedDescending:
        return(1)
    case .orderedSame:
        return(0)
    }
}

您无法获得正确日期的唯一情况是date为空或与您提到的日期格式不匹配。

不要强制 unwrap。安全地解包并处理无效日期输入的错误情况。


您可以查看此链接以获取有关日期格式的更多信息。

于 2018-08-23T06:26:22.193 回答
0

@rmaddy 是对的,更改hhHH有效:

func checkForDate(date: String?) -> Int{
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let fromDt = dateFormatter.date(from: date ?? "")
    let curreentDate = Date()
    let order = Calendar.current.compare(curreentDate , to: fromDt!, toGranularity: .day)
    switch order {
    case .orderedAscending:
        return(2)
    case .orderedDescending:
        return(1)
    case .orderedSame:
        return(0)
    }
}

也删除最后一个return 0,因为它永远不会执行。

于 2018-08-23T06:27:14.533 回答