日期格式崩溃

时间:2018-08-23 06:07:25

标签: ios swift date dateformatter

我在查看日期时崩溃:

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)

我得到nil的{​​{1}}

我的约会日期为fromDt

2 个答案:

答案 0 :(得分: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为空或与您提到的日期格式不匹配。

不要强行打开。安全打开包装并处理错误情况,以防止输入无效的日期。


您可以选中此link,以获取有关日期格式的更多信息。

答案 1 :(得分:0)

@rmaddy是正确的,将this.state = { form: {}, lastUser: null, }; // ... static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.user !== prevState.lastUser) { return { form: nextProps.user, lastUser: nextProps.user }; } return {}; } 更改为hh可以正常工作:

HH

还要删除最后一个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) } } ,因为它将永远不会执行。