Search code examples
iosswiftnsdateformatter

Convert date with nsdateformatter in swift 4


I have the following dates as String:

2018-06-14T23:00:00.000Z
2018-06-14T00:00:00.000Z

and I am trying to convert with this code:

let fecha_finConvert = convert_fecha(fecha: dateString)
func convert_fecha(fecha: String)-> String{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
    dateFormatter.locale = Locale.init(identifier: "es_EC")
    let dateObj = dateFormatter.date(from: fecha)
    dateFormatter.dateFormat = "dd 'de' MMM 'del' yyyy"
    let fecha_convert = dateFormatter.string(from: dateObj!)

    return fecha_convert
}

and that should return value as: 14 de Jun. del 2018

the first date returns good BUT with the second date returns 13 de Jun. del 2018

What is wrong? How can I solve that? thanks in advance


Solution

  • Both dates have the UTC (zero) timezone and they are being converted to your local time zone. Therefore the result is completely correct relative to your time zone.

    If you want to display the dates in UTC time zone, you can set the time zone explicitly on the formatter:

    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)