比较Swift中的ISO8601格式日期iOS版

时间:2018-01-16 19:26:42

标签: ios swift datetime nsdateformatter

我试图比较两个日期和时间(格式为ISO8601)。我已经实现了以下逻辑但是对象返回nil(这不会占用我需要的时间)。请告知需要做什么

例如:当两个日期" 2017-01-25T01:00:00.00"并且" 2018-01-25T01:00:00.00"进行比较,它应该在需要时间的情况下返回true(即secondDate> firstDate)

    //Date Formatter
    let dateFormatter = DateFormatter()
    let dateFormatString = "2017-01-25T01:00:00.00"
    dateFormatter.dateFormat = dateFormatString
    dateFormatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601)
    dateFormatter.locale = Locale(identifier: "en_EN_POSIX")
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

    //Get Dates from ISO8601 format 
    var dateString: Date?
    var dateFromAPI: Date?
    //Date from string value (defaultFirstDate is string value)
    if let firstDate = defaultFirstDate, let truncatedDate = firstDate.components(separatedBy: "T").first{ 
    //Issue is with below line - it returns nil
        dateString = dateFormatter.date(from: truncatedDate)
    }
    if let secondDate = defaultSecondDate, let truncatedDate = secondDate.components(separatedBy: "T").first { 
    //Issue is with below line - it returns nil
        dateFromAPI = dateFormatter.date(from: truncatedDate)
    }


    if let date1 = dateString, let date2 = dateFromAPI, date1.compare(date2) == ComparisonResult.orderedAscending {
        showPage = true
    }

0 个答案:

没有答案