我正在尝试从服务器响应中获取日期,如下所示:
“ dateStart”:“ 2019-08-21T14:54:03.285108Z”,
“ dateEnd”:“ 2019-09-20T06:15:03.285108Z”
由于我只需要日期和日期,所以结果应该是:“ 08-21”和“ 09-20”
我确实尝试过过滤结果,但是我崩溃了:
线程1:致命错误:无法与upperBound
形成范围
这是我的代码:
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
任何帮助将不胜感激!
答案 0 :(得分:0)
您首先应该使用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
}()
}
游乐场测试:
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
}