I think I see what you’re getting at here.
The problem is that
Date
represents a fixed point in time, so if you ask
DateFormatter
to parse a string that only contains
time components, it has to come up with some default values for the date. It does this using the
defaultDate
property. By default this is
nil
, which is treated like the start of the year 2000 UTC. Hence a date formatter with no date components will default to 1 Jan 2000.
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.timeZone = TimeZone(secondsFromGMT: 0)
df.dateFormat = "HH':'mm"
print(df.date(from: "12:34")!) // prints "2000-01-01 12:34:00 +0000"
IMPORTANT Using a value of
nil
for
defaultDate
is
not the same as using
Date(timeIntervalSinceReferenceDate: 0.0)
. The reference date used by
Date
is the start of the year 2001. I’m sure there’s a good reason for this mismatch (-:
If you want the date formatter to default to some other date, just set the
defaultDate
parameter.
df.defaultDate = Date(timeIntervalSinceReferenceDate: 561816000.0) // 2018-10-21 12:00:00 UTC
print(df.date(from: "12:34")!) // prints "2018-10-21 12:34:00 +0000"
WARNING In this example I’m force unwrapping the resulting date. That’s safe because every time is valid for every date in UTC. This is not true for all time zones, and that can cause problems on days where daylight savings time ‘springs forward’. For example:
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.timeZone = TimeZone(identifier: "Europe/London")
df.dateFormat = "HH':'mm"
df.defaultDate = Date(timeIntervalSinceReferenceDate: 543672000.0) // 2018-03-25 12:00:00 UTC
print(df.date(from: "01:30")) // prints nil
This is because the UK transitioned from GMT to BST on 25 Mar 2018, hence 01:30 does not exist on that day.
Beyond that, there are still problems associated with the locale. So far you’ve not clarified whether you’re working with fixed-format dates or localised dates. If it’s the former then hard coding
en_US_POSIX
is the right solution; if it’s the latter, things get more complex.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"