Keep Date-Only Values Stable In SwiftUI Forms

Your API sends 2026-10-14. You decode it as midnight UTC, show it on a phone in Denver, and the target day becomes October 13.

Nothing went wrong with the time-zone conversion. The wrong thing was converted.

Foundation’s Date represents an instant. A project target day is often just a label in a calendar. Formatting away the time, or asking for the start of a day, still leaves an instant underneath. A calendar date should not need a boarding pass to keep its name.

We will keep the API value as a validated Gregorian day, use a temporary Date only where SwiftUI’s picker requires one, and save a day again. The example targets iOS 17 or later, using the installed Swift 6.4 compiler. It does not require an OS 27 API.

Agree on what the server means

This example’s contract is deliberately narrow: an ASCII YYYY-MM-DD string, Gregorian calendar, years 1900 through 2100. That range is our example API’s rule, not a limit of the Gregorian calendar. Change it deliberately in both validation and the picker when your contract differs.

A date-only label is different from “all events on this day in Tokyo” or “send a reminder at 9 AM.” Those require a time zone and rules for turning the label into instants. Our working-day scheduling article covers that other boundary.

The Stack Overflow question about a date-only Swift type already has answers, including formatting and component-based types. The 2026 DayType discussion makes the calendar-label versus zoned-day distinction especially useful. We are building a small, original form example around that distinction, rather than introducing a new Foundation type or depending on DayType.

Download the complete sample and tests. The Swift blocks below also fit together, in order, in one iOS app file; the final block replaces its generated App declaration.

Validate the value, including decoding

DateComponents is useful for conversions, but its optional fields do not enforce this API’s complete-date contract. Give the domain value immutable fields and one validating initializer. Route decoding through it too: a carefully guarded initializer is little help if synthesized decoding can create February 31 through the side door.

import Foundation
import SwiftUI

// Deliberately scoped to modern Gregorian dates used by this example's API.
// This is not a universal calendar or a historical-date implementation.
nonisolated struct GregorianDay: Equatable, Hashable, Codable, Sendable {
    let year: Int
    let month: Int
    let day: Int
    enum Failure: Error { case invalid, unrepresentable }

    init(year: Int, month: Int, day: Int) throws {
        guard (1900...2100).contains(year), (1...12).contains(month) else { throw Failure.invalid }
        let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
        let lengths = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        guard (1...lengths[month - 1]).contains(day) else { throw Failure.invalid }
        self.year = year; self.month = month; self.day = day
    }

    init(wire: String) throws {
        let bytes = Array(wire.utf8)
        guard bytes.count == 10, bytes[4] == 45, bytes[7] == 45 else { throw Failure.invalid }
        let indices = [0, 1, 2, 3, 5, 6, 8, 9]
        guard indices.allSatisfy({ (48...57).contains(bytes[$0]) }) else { throw Failure.invalid }
        func integer(_ range: Range<Int>) -> Int {
            bytes[range].reduce(0) { $0 * 10 + Int($1 - 48) }
        }
        try self.init(year: integer(0..<4), month: integer(5..<7), day: integer(8..<10))
    }

    var wire: String {
        func padded(_ value: Int, _ width: Int) -> String {
            let digits = String(value)
            return String(repeating: "0", count: width - digits.count) + digits
        }
        return "\(padded(year, 4))-\(padded(month, 2))-\(padded(day, 2))"
    }

    init(from decoder: any Decoder) throws {
        let container = try decoder.singleValueContainer()
        let wire = try container.decode(String.self)
        do { try self.init(wire: wire) }
        catch { throw DecodingError.dataCorruptedError(in: container, debugDescription: "Expected a Gregorian YYYY-MM-DD date from 1900 through 2100") }
    }

    func encode(to encoder: any Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(wire)
    }

    static var pickerCalendar: Calendar {
        var calendar = Calendar(identifier: .gregorian)
        calendar.timeZone = TimeZone(secondsFromGMT: 0)!
        return calendar
    }

    // An implementation detail for the control, never the persisted domain value.
    func pickerCarrier() throws -> Date {
        guard let date = Self.pickerCalendar.date(from: DateComponents(year: year, month: month, day: day, hour: 12)),
              try Self(pickerCarrier: date) == self else { throw Failure.unrepresentable }
        return date
    }

    init(pickerCarrier: Date) throws {
        let components = Self.pickerCalendar.dateComponents([.year, .month, .day], from: pickerCarrier)
        guard let year = components.year, let month = components.month, let day = components.day else { throw Failure.unrepresentable }
        try self.init(year: year, month: month, day: day)
    }
}

The wire parser accepts exactly ten ASCII bytes in the agreed shape. It rejects whitespace, timestamp suffixes, missing padding, and lookalike digits. Its custom encoder writes a JSON string, not an object containing three fields or an epoch timestamp.

The leap-year rule handles the century exception: 2000 has February 29; 1900 and 2100 do not. We validate before asking Calendar to construct an instant, then check the conversion back to components. Calendar construction is not our wire validator.

pickerCarrier() creates noon in a fixed Gregorian/UTC calendar. Noon is just a convenient internal value. UTC and the matching conversion calendar establish the boundary; noon in an arbitrary local zone cannot rescue every skipped civil day. Never send this carrier to the server as a timestamp.

Give the picker whole-day bounds

DatePicker still binds to a Date when displayedComponents contains only .date. We need the picker and the save conversion to agree on their calendar and zone.

An edit session prepares the temporary value and a range covering the entire first and last supported day. Using noon for both bounds would unnecessarily exclude earlier hours of the first day and later hours of the last one, even though the control hides those hours.

nonisolated struct DayEditSession: Identifiable {
    let id = UUID()
    let initialCarrier: Date
    let bounds: ClosedRange<Date>

    init(day: GregorianDay) throws {
        let calendar = GregorianDay.pickerCalendar
        guard let first = calendar.date(from: DateComponents(
            year: 1900, month: 1, day: 1
        )), let afterLast = calendar.date(from: DateComponents(
            year: 2101, month: 1, day: 1
        )) else { throw GregorianDay.Failure.unrepresentable }

        initialCarrier = try day.pickerCarrier()
        // Include every hour of both endpoint days.
        let last = Date(timeIntervalSinceReferenceDate:
            afterLast.timeIntervalSinceReferenceDate.nextDown
        )
        bounds = first...last
    }
}

nextDown selects the preceding representable time interval, making the inclusive upper bound the last representable instant before January 1, 2101. It also includes the last fractional second of December 31. These are fixed-UTC control bounds, not an algorithm for finding the end of an arbitrary local day. The domain initializer still validates the selected components when saving.

Keep edits local until Save

struct DayEditor: View {
    @State private var carrier: Date
    @State private var errorMessage: String?
    private let bounds: ClosedRange<Date>
    let onSave: (GregorianDay) -> Void
    let onCancel: () -> Void

    init(
        session: DayEditSession,
        onSave: @escaping (GregorianDay) -> Void,
        onCancel: @escaping () -> Void
    ) {
        _carrier = State(initialValue: session.initialCarrier)
        bounds = session.bounds
        self.onSave = onSave
        self.onCancel = onCancel
    }

    var body: some View {
        VStack(spacing: 20) {
            DatePicker(
                "Target day (Gregorian)", selection: $carrier,
                in: bounds, displayedComponents: .date
            )
            .datePickerStyle(.wheel)
            .environment(\.calendar, GregorianDay.pickerCalendar)
            .environment(\.timeZone, GregorianDay.pickerCalendar.timeZone)

            if let errorMessage { Text(errorMessage) }
            HStack {
                Button("Cancel", action: onCancel)
                Spacer()
                Button("Save") {
                    do { onSave(try GregorianDay(pickerCarrier: carrier)) }
                    catch { errorMessage = "Choose a supported calendar date." }
                }
            }
        }
        .padding()
    }
}

Only Save calls onSave. Cancel never converts or publishes the draft. The picker receives a Gregorian calendar and UTC explicitly, while its display locale remains the user’s locale. The label makes that calendar choice visible instead of silently pretending to support alternate-calendar entry.

This example deliberately uses the wheel style. A compact or graphical picker may have different interaction details; test your chosen style and endpoints before substituting it. The same applies if your product lets people enter dates in another calendar: conversion is a feature to design, not a formatter flag to sprinkle on afterward.

Make each edit a fresh session

struct TargetDayForm: View {
    @State private var savedDay: GregorianDay
    @State private var edit: DayEditSession?
    @State private var errorMessage: String?

    init(initialDay: GregorianDay) {
        _savedDay = State(initialValue: initialDay)
    }

    var body: some View {
        VStack(spacing: 20) {
            Text("Saved API value: \(savedDay.wire)")
            Button("Edit target day") {
                do { edit = try DayEditSession(day: savedDay); errorMessage = nil }
                catch { errorMessage = "The date editor could not be opened." }
            }
            if let errorMessage { Text(errorMessage) }
        }
        .padding()
        .sheet(item: $edit) { session in
            DayEditor(session: session, onSave: { day in
                savedDay = day
                edit = nil
            }, onCancel: {
                edit = nil
            })
            .id(session.id)
        }
    }
}

The form owns the saved day; the sheet owns its draft. Dismissing the sheet without Save also discards the edit. Reopening creates a fresh session from the latest saved value. Apple’s id(_:) contract resets a view’s state when its identity changes; the session ID gives that boundary a concrete owner.

initialDay seeds this form’s state once. It is not a subscription to later parent values. If you reuse the form for a different record, give it that record’s identity with .id(recordID), or explicitly load a new draft at that boundary. Do not assign a fresh random identity on every body evaluation: that would throw away active edits.

The saved wire string is displayed here to make the example inspectable. A shipping screen can show a localized date using the same explicit calendar/zone. Its persistence or API layer should encode GregorianDay, never the temporary picker value. This demo does not implement network saves, conflict resolution, or durable storage.

Decode at the entry point

@main
struct DateOnlyDemoApp: App {
    private let loadedDay = Result {
        try JSONDecoder().decode(
            GregorianDay.self, from: Data(#""2026-10-14""#.utf8)
        )
    }

    var body: some Scene {
        WindowGroup {
            switch loadedDay {
            case .success(let day):
                TargetDayForm(initialDay: day)
            case .failure:
                ContentUnavailableView(
                    "Invalid target day", systemImage: "calendar.badge.exclamationmark"
                )
            }
        }
    }
}

An invalid server string becomes a load failure before the editor opens. There is no fallback to “today” that quietly replaces bad data with a plausible date.

Test the day, not just the formatted text

The useful assertions are about saved components and encoded bytes, as well as the control:

CaseExpected result
2000-02-29Accepted and round-trips
1900-02-29, 2100-02-29, or April 31Rejected by construction and decoding
Full-width digits, whitespace, or a timestamp suffixRejected by the strict wire parser
First and last supported picker daySaved without a hidden-hour exclusion
Edit, Cancel, then reopenOriginal saved day appears
Change locale, calendar, or time zone around the formGregorian saved value stays the same
Open another record with a new form identityThat record supplies the new initial value

The five final Swift blocks compile and link with Xcode 27.0 / Swift 6.4, targeting iOS 17, in Swift 6 mode with warnings as errors under ordinary and MainActor default isolation. The domain checks cover all 73,414 supported calendar dates, comparing valid days with Foundation and round-tripping the wire string, JSON, and picker carrier. They pass on macOS 27.0.1 and iOS 27 Simulator in both modes.

The native tests use the exact form and editor declarations. They exercise wheel changes, Save, Cancel, swipe dismissal, reopening, another record’s identity, and both range endpoints. They also change the surrounding SwiftUI locale/calendar/time-zone environment from English/Gregorian/Denver to Thai/Buddhist/Kiritimati and back while verifying the saved Gregorian value. Those are app-injected environments, not changes to device system settings. Native execution was on iOS 27 Simulator; iOS 17 is the checked deployment target, not a tested runtime. No physical-device or alternate-picker-style testing is claimed.

Use an instant when the product means an instant. When the API means a calendar label, preserve that meaning all the way through the form.