Search code examples
jsonswifttimezonedateformatter

How to parse ISO8061 to date without timezone


I receive data from the server in the JSON format and one field is date which holds year, month and day:

"date": "2018-03-11",

I don't need exact time, just day and month. I used a DateFormatter with locale but I'm still receiving date from the UTC timezone. I live in CET (+1)/ CEST (+2) timezone so I wonder what is the best approach to parse this date. When I receive "2018-03-11" from server I would like to get:

date = 2018-03-11 00:00:00

date formatter:

private let dateFormatter: DateFormatter = {
       let dateFormatter = DateFormatter()
        dateFormatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601)
        dateFormatter.locale = Locale(identifier: "pl_PL")

        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter
    }()

Solution

  • Just use

        dateFormatter.locale = Locale.current
        dateFormatter.timeZone = TimeZone.init(identifier: "UTC")
    
    let dateFormatter: DateFormatter = {
                let dateFormatter = DateFormatter()
                dateFormatter.locale = Locale.current
                dateFormatter.timeZone = TimeZone.init(identifier: "UTC")
                dateFormatter.dateFormat = "yyyy-MM-dd"
                return dateFormatter
            }()
    
        print(dateFormatter.date(from: "2018-03-11"))