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
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)
In your time string - 2018-06-14T00:00:00.000Z
- you specify time zone - Z
stands for Zulu
time, which basically means UTC
time zone.
When you convert your dateObj
to a string, you need to specify timeZone
property of your dateFormatter
. If you don't specify it, it defaults to system time zone. I'm guessing your device's time zone is not UTC
, hence the difference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.