gpt4 book ai didi

ios - 无法形成范围与 upperBound < lowerBound

转载 作者:可可西里 更新时间:2023-11-01 01:47:39 30 4
gpt4 key购买 nike

我正在尝试从如下所示的服务器响应中获取日期:

"dateStart": "2019-08-21T14:54:03.285108Z",

"dateEnd": "2019-09-20T06:15:03.285108Z"

因为我只需要日期和月份,所以结果将是:“08-21”和“09-20”

我确实尝试过过滤结果,但我遇到了崩溃:

Thread 1: Fatal error: Can't form Range with upperBound < lowerBound

这是我的代码:

    let startTime = dealStatus["dateStart"] as? String
let startFirst = startTime!.index(startTime!.startIndex, offsetBy: 5)
let endFirst = startTime!.index(startTime!.endIndex, offsetBy: -17)
let startTimeString = startTime![startFirst..<endFirst] // Getting crash here

let endTime = dealStatus["dateEnd"] as? String
let startSecond = endTime!.index(endTime!.startIndex, offsetBy: 5)
let endSecond = endTime!.index(endTime!.endIndex, offsetBy: -17)
let endTimeString = endTime![startSecond..<endSecond]

let startReplaced = startTimeString.replacingOccurrences(of: "-", with: ".")
let endReplaced = endTimeString.replacingOccurrences(of: "-", with: ".")
let startEndDates = "(" + String(startReplaced) + " - " + String(endReplaced) + ")"
//
let orderTitle = ordersResponseArray[indexPath.row]
let catTitle = orderTitle["title"] as? String
cell.titleAndDatesLabel.text = catTitle! + " " + startEndDates

如有任何帮助,我们将不胜感激!

最佳答案

您应该首先使用 DateFormatter 或 ISO8601DateFormatter 将 UTC 时间的日期字符串解析为日期对象,并从生成的日期中获取月和日表示形式:

extension Formatter {
static let monthDay: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MM.dd"
return dateFormatter
}()
}

extension Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}

Playground 测试:

let dealStatus: [String: Any] = ["dateStart": "2019-08-21T14:54:03.285108Z",
"dateEnd" : "2019-09-20T06:15:03.285108Z"]

if let dateStart = dealStatus["dateStart"] as? String,
let dateEnd = dealStatus["dateEnd"] as? String,
let start = Formatter.iso8601.date(from: dateStart),
let end = Formatter.iso8601.date(from: dateEnd) { // ,
// let catTitle = ordersResponseArray[indexPath.row]["title"] as? String {

let startTime = Formatter.monthDay.string(from: start)
let endTime = Formatter.monthDay.string(from: end)
let startEndDates = "(" + startTime + " - " + endTime + ")"
print(startEndDates) // "(08.21 - 09.20)"
// cell.titleAndDatesLabel.text = catTitle + " " + startEndDates
}

关于ios - 无法形成范围与 upperBound < lowerBound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57021450/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com