我正在从 JSON 解析日期。从 url 解析 JSON 日期后,我想从中获取最近 30 个日期。
Alamofire.request("url") .responseJSON { response in
if let arr = response.result.value as? [String:AnyObject]
{
let inrc = (arr["date"])!
self.myfuncDate(str: inrc as! String)
}
}
func myfuncDate(str: String)
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: str)
currrentDate = date
//currentDate is globalVariable
}
我在这里打印过去 30 天的数据。
for i in 1..<31
{
let day:String = String(cal.component(.day, from: currrentDate))
days.append(day)
print(days)
Output : ["13", "12", "11", "10", "9", "8", "7", "6",
"5", "4", "3", "2", "1", "31", "30", "29", "28", "27", "26", "25", "24",
"23", "22", "21", "20", "19", "18", "17", "16", "15"]
}
我想以日期的形式打印出来。
For Example: ["13-01-2017", "12-01-2017", "11-01-2017", "10-01-2017"...]
请帮帮我。
最佳答案
您可以通过这种方式获取 date 的最后 30 个日期:
var today = Date()
var dateArray = [String]()
for i in 1...30{
let tomorrow = Calendar.current.date(byAdding: .day, value: -1, to: today)
let date = DateFormatter()
date.dateFormat = "dd-MM-yyyy"
var stringDate : String = date.string(from: today)
today = tomorrow!
dateArray.append(stringDate)
}
print(dateArray)
输出:
["13-01-2017", "12-01-2017", "11-01-2017", "10-01-2017", "09-01-2017", "08-01-2017", "07-01-2017", "06-01-2017", "05-01-2017", "04-01-2017", "03-01-2017", "02-01-2017", "01-01-2017", "31-12-2016", "30-12-2016", "29-12-2016", "28-12-2016", "27-12-2016", "26-12-2016", "25-12-2016", "24-12-2016", "23-12-2016", "22-12-2016", "21-12-2016", "20-12-2016", "19-12-2016", "18-12-2016", "17-12-2016", "16-12-2016", "15-12-2016"]
试试这个,它可能对你有帮助。
关于json - 如何使用 swift 3.0 从日期中获取最近 30 个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41628667/