Multiple times during your development career, you need to format given dates according to ISO 8601 specification. That’s a standard to specify date, time and zone.
Since iOS10, we can use ISO8601DateFormatter
to handle this the easy way.
Sometimes, you run into issues that what you see is not always what you expect at first sight. I created a small playground to verify the timezone behaviour easily.
An important character you see in this specification is Z. It refers to Zulu time, a term used in military to refer to UTC+0. UTC is not an acronym but stands for coordinated universal time, formerly known as Greenwich Mean Time (GMT).
import UIKit
// Playground for testing the outcome of the displayed date given a stored ISO8601 date
var storedZuluDate = "2020-08-19T22:00:00Z" // Z(ulu) time or UTC+0
let iso8601Formatter = ISO8601DateFormatter()
let isoFormattedZuluDate = iso8601Formatter.date(from: storedZuluDate)
print(isoFormattedZuluDate ?? "date could not be parsed according to ISO8601 standard")
// Display the parsed date for a given Locale (Dutch (Belgium))
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "nl-BE")
formatter.dateFormat = "dd LLLL yyyy HH:mm"
print(formatter.string(from: isoFormattedZuluDate!))
The result you see in the console is:
// 2020-08-19 22:00:00 +0000
// 20 augustus 2020
This may look strange at first sight. But in summertime, Belgium is UTC+2 so 22:00 will become 24:00, a new day. Hence 20 august 2020 will be shown int the app and is perfectly fine.
So remember that both date and time you see at mobile apps could differ due to the used timezone and can introduce confusion at some point while just looking at date or time without taking the timezone into account.
As this can be very hard to explain in a simple way to new developers and non technical people, better be prepared with some samples.
var storedDate = "2020-08-19T22:00:00+02:00"
let isoFormattedDate = iso8601Formatter.date(from: storedDate)
print(isoFormattedDate ?? "date could not be parsed according to ISO8601 standard")
print(formatter.string(from: isoFormattedDate!))
The result you see in the console is:
// 2020-08-19 20:00:00 +0000
// 19 augustus 2020 22:00
While debugging or printing a date to the console, notice it will always show the date time at +0000 which refers to UTC+0 or Zulu time!
Don’t take DateTime parsing and formatting for granted and investigate some time in it to have a good understanding. You will even benefit from this knowledge in other programming languages as well.