Search code examples
swiftswift3

Swift 3 is there a way to print date as Date not as String


I'm trying to form a body with date parameter which i have to send to an api. Date gets printed as String format, is there a way to send it as only date format.

    let isoDate = "2019-09-21"
    let dateFormatter = DateFormatter()

    dateFormatter.dateFormat = "yyyy-MM-dd"
    let date = dateFormatter.date(from:isoDate)!

    let dateStr = dateFormatter.string(from: date)

    let body: [String: Any] = [
        "date": dateStr
    ]
    print(body)

It prints :

["date": "2019-09-21"]

I want it to print it as :

["date": 2019-09-21]

Solution

  • I was able to achieve this using the below code :

        let isoDate = "2019-09-21"
    
        let body: [String: AnyObject] = [
            "date": isoDate as AnyObject
        ]
        print(body)
    

    This now prints :

    ["date": 2019-09-21]