
In the previous section, we’ve looked at how you can convert a date to string. How do you convert a string datetime calculator online back to a Date object? That’s what we’ll discuss in this section.
Why would you want to convert strings to dates? A few scenarios:
You’ve received a well-formatted ISO 8601 string from a JSON-based webservice, and you need to convert it to a Date in Swift
You’ve stored a Unix timestamp in a database, that you need to parse to Date, and subsequently display to your app’s users
Data you’re working with has some obscure date formatting, that you want to parse, and write back in a more sensible format
The good news is that parsing date strings, and converting them to Date objects, is as simple as working with a DateFormatter object. The bad news is that parsing date strings has a ton of caveats and exceptions.
let formatter = DateFormatter()
formatter.dateFormat = “dd-MM-yyyy HH:mm:ss Z”
let datetime = formatter.date(from: “13-03-2020 13:37:00 +0100”)
print(datetime!)
// Output: 2020-03-13 12:37:00 +0000
In the above code, we’ve created a date/time format: day-month-year and hour-minute-second-timezone. We’re using double digit padding, i.e. 1 AM is written as 01:00. With the function date(from:) we’re using the formatter to convert a string to the datetime object, of type Date, which is printed out.
If you look closely, you can already see a discrepancy between the date string and the printed Date object. We’ve specified 13:37, but when datetime is printed out, we’re getting a 12:37 back. Why is that?
The Mac that I ran the above code on is set to the Central European Time (CET), which is one hour past Coordinated Universal Time (UTC). Based on the +0000, we can also see that the printed datetime object doesn’t have a timezone offset – so it’s in UTC.
Differently said, we input the time in the CET timezone, but it’s printed back in the UTC (-1 hour) timezone. The Date object and the date/time strings are referencing the same point in time, though. It’s the formatting that’s different! Confusing.
You can verify a Mac or iPhone’s timezone with this code:
let tz = TimeZone.current
print(tz)
// Output: Europe/Amsterdam (current)
We can assert that the date/time string 13-03-2020 13:37 was parsed with the CET timezone. After conversion, when printed, it was output in the UTC timezone. Hence the one hour difference. Good to know!
Can we print out the date/time in the correct timezone? Yes! First off all, it’s smart to provide timezone information whenever you’re working with date/time strings. That way you can avoid any confusion around the string’s timezone and your system’s timezone.
Leave a comment