如何获得最后 30 日期从日期使用 swift 3.0

标签: json Swift
发布时间: 2017/2/28 23:53:50
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我解析从 JSON 的日期。在解析 JSON 日期从 url 之后, 想要从那得到最后 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"...]

请帮我。

解决方法 1:

你可以从日期以这种方式获取最后 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"]

试试这个它可能帮助你。

赞助商