Ios 仅从日期数组中删除时间
我从这样的api获取日期:Ios 仅从日期数组中删除时间,ios,swift,Ios,Swift,我从这样的api获取日期: ["2019-07-12 12:43:00", "2019-07-09 12:57:35", "2019-07-09 12:04:33", "2019-07-05 14:32:32", "2019-07-04 17:50:23", "2019-07-02 12:12:30", "2019-07-01 18:09:28"] let dateArray = ["2019-07-12 12:43:00", "2019-07-09 12:57:35", "2019-07-0
["2019-07-12 12:43:00", "2019-07-09 12:57:35", "2019-07-09 12:04:33", "2019-07-05 14:32:32", "2019-07-04 17:50:23", "2019-07-02 12:12:30", "2019-07-01 18:09:28"]
let dateArray = ["2019-07-12 12:43:00", "2019-07-09 12:57:35", "2019-07-09 12:04:33", "2019-07-05 14:32:32", "2019-07-04 17:50:23", "2019-07-02 12:12:30", "2019-07-01 18:09:28"]
let onlyDatesArray = dateArray.compactMap({ $0.components(separatedBy: " ")[0] })
print("only dates -> \(onlyDatesArray)")
但是我想要的是,我想要从这个日期数组中删除时间,以得到这样的日期
["2019-07-12", "2019-07-09", "2019-07-09", "2019-07-05", "2019-07-04", "2019-07-02", "2019-07-01"]
我想要这样的结果
["2019-07-12", "2019-07-09", "2019-07-09", "2019-07-05", "2019-07-04", "2019-07-02", "2019-07-01"]
之所以需要,是因为我需要在
FSCalendar
上显示事件。我该怎么做 请检查以下代码:
let arr = ["2019-07-12 12:43:00", "2019-07-09 12:57:35", "2019-07-09 12:04:33", "2019-07-05 14:32:32", "2019-07-04 17:50:23", "2019-07-02 12:12:30", "2019-07-01 18:09:28"]
var arrOnlyDates = [String]()
for (_,str) in arr.enumerated(){
let s = str.components(separatedBy: " ")
arrOnlyDates.append(s[0])
}
print(arrOnlyDates)
您只需按如下方式获取日期数组:
["2019-07-12 12:43:00", "2019-07-09 12:57:35", "2019-07-09 12:04:33", "2019-07-05 14:32:32", "2019-07-04 17:50:23", "2019-07-02 12:12:30", "2019-07-01 18:09:28"]
let dateArray = ["2019-07-12 12:43:00", "2019-07-09 12:57:35", "2019-07-09 12:04:33", "2019-07-05 14:32:32", "2019-07-04 17:50:23", "2019-07-02 12:12:30", "2019-07-01 18:09:28"]
let onlyDatesArray = dateArray.compactMap({ $0.components(separatedBy: " ")[0] })
print("only dates -> \(onlyDatesArray)")
您可以简单地组合使用
compactMap(:)
和组件(分隔符:)
等
let arr = ["2019-07-12 12:43:00", "2019-07-09 12:57:35", "2019-07-09 12:04:33", "2019-07-05 14:32:32", "2019-07-04 17:50:23", "2019-07-02 12:12:30", "2019-07-01 18:09:28"]
let result = arr.compactMap({ $0.components(separatedBy: " ").first })
由于日期格式没有改变,所以只需从每个字符串中去掉前10个字符
let dates = ["2019-07-12 12:43:00", "2019-07-09 12:57:35", "2019-07-09 12:04:33", "2019-07-05 14:32:32", "2019-07-04 17:50:23", "2019-07-02 12:12:30", "2019-07-01 18:09:28"]
let datesWithoutTime = dates.map{ String($0.prefix(10)) }
这些都是字符串吗?他们有固定的格式吗?你能只看前10个字符吗?-你肯定试过了,不要犹豫,展示你的尝试吧!使用日期转换它formatter@MartinR....Yes它们都是字符串,所有日期的格式都是相同的,我尝试了这个答案,但没有显示致命错误如果所有的字符串都是字符串,那么使用第一个对象并将其存储到数组中all@Anbu.Karthik... 我看到了这个答案,但它们都只是拆分一个字符串而不是数组。如果只丢弃偏移量,为什么要使用
enumerated()
?