You Saved the User's Birthday as a Date. Now It's a Day Early for Everyone in America.
My birthday reminder app wished a user in Chicago a happy birthday on the wrong day. Not a random wrong day. The day before. Every single American user, every single time.
I live in Central Europe. On my phone, every birthday was perfect. That’s the thing about this bug: it only shows up for people west of wherever you happen to be sitting, and your test devices are sitting with you.
A birthday isn’t a moment
Swift’s Date is a single instant on the universe’s timeline. It’s a number of seconds since a reference point. It has no idea what a “day” is, what time zone you’re in, or that you were born.
A birthday is something else entirely. It’s a square on a paper calendar. March 5th is March 5th whether you’re in Berlin, Chicago, or on a plane over Greenland. Nobody celebrates their birthday “from 23:00 UTC on the 4th until 22:59 UTC on the 5th.”
When you squeeze a calendar square into a Date, you have to pick an instant to represent it. The usual pick is midnight. Midnight where, though? Whatever time zone the device had at the moment of saving. That choice gets baked in silently, and it comes back to bite you the moment the time zone changes.
Watch it happen
Here’s the whole bug in a handful of lines. A user in Berlin picks March 5th. Later, they move to New York (or just fly there for work):
import Foundation
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(identifier: "Europe/Berlin")!
let birthday = calendar.date(from: DateComponents(year: 1990, month: 3, day: 5))!
print(birthday) // 1990-03-04 23:00:00 +0000
calendar.timeZone = TimeZone(identifier: "America/New_York")!
print(calendar.component(.day, from: birthday)) // 4
Midnight in Berlin is 11 PM the previous evening in UTC, which is 6 PM the previous evening in New York. Same instant, different square on the calendar. Nothing about the stored value is wrong. The type is wrong.
The server version is even sneakier
The travel case at least needs someone to travel. The server case hits people sitting on their couch.
Your API sends "birthday": "1990-03-05", which is a perfectly honest date-only string. Then the app parses it like this:
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withFullDate]
let date = formatter.date(from: "1990-03-05")!
// 1990-03-05 00:00:00 +0000 ← midnight UTC
ISO8601DateFormatter defaults to GMT. So you get midnight UTC, and then you display it with a normal DateFormatter or .formatted(date: .long, time: .omitted), which uses the device’s time zone. In London, fine. In Berlin, fine (it’s 1 AM on the 5th). In Chicago, it’s 6 PM on March 4th.
That’s why my European phone never saw it. Everyone east of UTC rounds forward into the right day. Everyone west of UTC rounds back into the wrong one. If your team is in Europe and your users are in the US, you’ve built the perfect bug-hiding machine.
I’ve written before about server date strings that break JSONDecoder and about what JSONEncoder does to a Date by default. This one is worse than both, because nothing fails. It decodes cleanly into the wrong answer.
Where this shows up
Birthdays are the classic, but the pattern is everywhere:
- Due dates on invoices and tasks (“due March 31” becomes “overdue” a few hours early).
- All-day events and holidays in a custom calendar view.
- Habit trackers and streaks, where “did they log today” depends on which day today is.
- Passport and license expiry dates in a travel app, used by people who, famously, travel.
- Date of birth for age checks, where off-by-one can flip someone under 18.
The question to ask about every date property in your model is simple: is this an instant or a calendar day? “When the user tapped Save” is an instant. “The day the invoice is due” is a square on the wall. Only the first one belongs in a Date.
The fix: store the square, not the instant
Make the type say what the value actually is. Here’s the struct I use:
import Foundation
struct LocalDate: Hashable, Comparable, Sendable {
let year: Int
let month: Int
let day: Int
init(year: Int, month: Int, day: Int) {
self.year = year
self.month = month
self.day = day
}
/// The calendar day `date` falls on, as seen from `calendar`'s time zone.
init(_ date: Date, in calendar: Calendar = Calendar(identifier: .gregorian)) {
let parts = calendar.dateComponents([.year, .month, .day], from: date)
self.init(year: parts.year!, month: parts.month!, day: parts.day!)
}
/// Midnight of this day in `calendar`'s time zone. Only for display and pickers.
func date(in calendar: Calendar = Calendar(identifier: .gregorian)) -> Date? {
calendar.date(from: DateComponents(year: year, month: month, day: day))
}
static func < (lhs: LocalDate, rhs: LocalDate) -> Bool {
(lhs.year, lhs.month, lhs.day) < (rhs.year, rhs.month, rhs.day)
}
}
Calendar(identifier: .gregorian) picks up the device’s current time zone by default, which is exactly what you want at the moment of display. I use the Gregorian identifier explicitly rather than Calendar.current, because the user’s calendar setting can be Buddhist or Japanese, and year: 1990 means something different there.
Make it encode as the same "yyyy-MM-dd" string your server already speaks:
extension LocalDate: Codable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let raw = try container.decode(String.self)
let parts = raw.split(separator: "-").compactMap { Int($0) }
guard parts.count == 3 else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Expected yyyy-MM-dd, got \(raw)"
)
}
self.init(year: parts[0], month: parts[1], day: parts[2])
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(String(format: "%04d-%02d-%02d", year, month, day))
}
}
No time zone appears anywhere in the stored value, because there isn’t one. "1990-03-05" goes in, "1990-03-05" comes out, on every device on Earth.
Converting at the edges
Date doesn’t disappear. SwiftUI’s DatePicker still wants one. The trick is to convert at the boundary and never let the Date leak into your model:
import SwiftUI
struct BirthdayField: View {
@Binding var birthday: LocalDate
var body: some View {
DatePicker(
"Birthday",
selection: Binding(
get: { birthday.date() ?? .now },
set: { birthday = LocalDate($0) }
),
displayedComponents: .date
)
}
}
The picker shows midnight of the stored day in whatever time zone the phone has right now, and the setter reads the day back in that same zone. Round trip, no drift.
For SwiftData, here’s how I’d do it: persist a String key like "1990-03-05" next to (or instead of) the struct. Zero-padded ISO strings sort correctly as plain strings, and they work in a #Predicate without any custom type gymnastics.
Reminders get the same treatment. A yearly birthday notification shouldn’t be a Date either:
let trigger = UNCalendarNotificationTrigger(
dateMatching: DateComponents(month: birthday.month, day: birthday.day, hour: 9),
repeats: true
)
Date components in a calendar trigger are floating: they mean “9 AM on March 5th wherever this phone is.” Which is what a human means too. That one change is what actually fixed my Chicago users.
The noon hack
You’ll see this advice on forums: “Just store the date at noon instead of midnight. Twelve hours of slack in both directions, problem solved.”
It’s a clever hack, and it mostly works. Noon in Berlin is 11:00 UTC. Shift that to UTC−12 and it’s still the same calendar day. But Kiribati sits at UTC+14, and Samoa and Tonga at UTC+13. From Berlin’s noon, Kiribati is already at 1 AM tomorrow. The world’s offsets span 26 hours, not 24, so no single instant lands on the same calendar day everywhere.
That’s maybe a few hundred thousand people. It’s also exactly the kind of “rare” that lands as a one-star review titled “wrong date??” from someone who will never tell you where they live. The noon hack shrinks the bug. It doesn’t remove it. A struct with three integers removes it.
The same goes for the other classic “fix,” adding 86,400 seconds or doing math on the raw TimeInterval. I wrote a whole post about why adding 86,400 seconds is not adding a day. Once you have a LocalDate, do date arithmetic through Calendar and convert back.
The test that would have caught it
The reason this survives code review is that every test runs in one time zone: yours. So pin the time zone in the test, and run it in the zones that hurt:
import Testing
import Foundation
struct LocalDateTests {
@Test(arguments: [
"Europe/Berlin", "America/Los_Angeles",
"Pacific/Kiritimati", "Pacific/Pago_Pago", "Asia/Kolkata"
])
func dayRoundTripsInEveryZone(zoneID: String) throws {
let saved = LocalDate(year: 1990, month: 3, day: 5)
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = try #require(TimeZone(identifier: zoneID))
let shown = try #require(saved.date(in: calendar))
#expect(LocalDate(shown, in: calendar) == saved)
}
@Test func encodesAsPlainDateString() throws {
let data = try JSONEncoder().encode([LocalDate(year: 1990, month: 3, day: 5)])
#expect(String(decoding: data, as: UTF8.self) == #"["1990-03-05"]"#)
}
}
Kiritimati is UTC+14, Pago Pago is UTC−11, and Kolkata is +5:30 to catch anyone doing whole-hour math. If your old Date-based model is still around, write the same test against it first and watch it fail in Los Angeles. That red test is the best argument you’ll ever bring to a “do we really need a new type?” meeting.
It’s also a nice prompt pattern when you’re debugging with an AI assistant: ask it to “parameterize this test over time zones on both sides of UTC” rather than “check if this date code is right.” The first gets you evidence. The second gets you reassurance.
The rule
Before you type var something: Date, say the property’s name out loud and ask whether it happens at a moment or on a day. Timestamps, deadlines with a time, “last synced” all happen at a moment. Birthdays, due dates, holidays happen on a day.
If you have to pick a time zone to make it a Date, it was never a Date. Store the square on the calendar, and let every phone hang it on its own wall.
Share this post
Comments
Leave a comment
NativeFirst Team
EditorialThe NativeFirst team — engineers and designers building native Apple apps and writing the courses we wish we had when we started.