获取当前月份&年和传递到API iOS Swift?

时间:2017-10-05 18:01:43

标签: ios json api swift3

我有一个功能,我必须通过当前月份&在Swift 3中获取API的年份参数。如果我在参数中传递hardCode,我得到儿子的响应,但我无法用当前月份和年。代码: -

func raffleNumberGenerate(){
    let prs = [
        "month":currentMonth,
        "year" : currentYear,
        "raffle_result": "1" as String
    ]
    Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
        let jsonResponseSingle = result as? NSDictionary
        print(" JSON Response :- \(String(describing: jsonResponseSingle))"
}

提前致谢。

2 个答案:

答案 0 :(得分:4)

您没有currentMonthcurrentYear的值,所以您必须制作一些。

func raffleNumberGenerate() {
    let date = Date() // gets current date
    let calendar = Calendar.current
    let currentYear = calendar.component(.year, from: date) // gets current year (i.e. 2017)
    let currentMonth = calendar.component(.month, from: date) // gets current month (i.e. 10)

    let prs = [
        "month":currentMonth,
        "year" : currentYear,
        "raffle_result": "1" as String
    ]

    Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
        let jsonResponseSingle = result as? NSDictionary
        print(" JSON Response :- \(String(describing: jsonResponseSingle))"
    }
}

现在你应该可以做任何你需要做的JSON。我应该注意currentMonthcurrentYear现在属于Int类型,如果您需要它们作为字符串,您只需转换为String(currentMonth)String(currentYear)。 / p>

答案 1 :(得分:0)

let today = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy"
let year = dateFormatter.string(from: today)
dateFormatter.dateFormat = "MM"
let month = dateFormatter.string(from: today)

e.g。年= 2017月= 10

per @maddy

var calendar = NSCalendar.current
let today = Date()
let desiredComponents = Set<Calendar.Component>([.month, .year])
calendar.timeZone = TimeZone(identifier: "UTC")!
let components = calendar.dateComponents(desiredComponents, from: today)
components.year
components.month