// The app's ONE way of reading and writing an instant, and the app's one way of // reading a calendar day — stated once, in the module every other one links // (CottonValues: Foundation alone, so a face reads a stamp with no core). // // `CottonUI` and the share extension read stamps the crate wrote and // write stamps the crate will read, and until this file each did it with its // own formatter and its own option set. The spellings for a SCREEN (a house // time, a weekday date) are `CottonUI`'s `DateFormats`; what lives here is the // wire and the calendar, which is what an extension with no screens needs. // // EVERY function takes its `Calendar`; nothing reads `Calendar.current` from // inside except as the call site's default. A fixed-`now` test over a function // that defaulted to the clock is a time bomb with a computable detonation date. import Foundation public enum CottonDate { private struct FormatterKey: Hashable { let pattern: String let calendar: Calendar } private final class ThreadFormatters { let fractional: ISO8601DateFormatter let plain: ISO8601DateFormatter var patterns: [FormatterKey: DateFormatter] = [:] init() { fractional = ISO8601DateFormatter() fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds] fractional.timeZone = TimeZone(secondsFromGMT: 0) plain = ISO8601DateFormatter() plain.formatOptions = [.withInternetDateTime] plain.timeZone = TimeZone(secondsFromGMT: 0) } } // Accessed synchronously, with no suspension or formatter escaping to a // different thread. A static mutable formatter would race; constructing // one per row dominated the main-thread Messages opening profile. private static var threadFormatters: ThreadFormatters { let key = "com.cottondb.CottonDate.formatters" let dictionary = Thread.current.threadDictionary if let found = dictionary[key] as? ThreadFormatters { return found } let made = ThreadFormatters() dictionary[key] = made return made } // Identities/counts let the performance guards prove reuse and isolation // without exposing any mutable formatter from the private cache. static var formatterCacheIdentity: ObjectIdentifier { ObjectIdentifier(threadFormatters) } static var cachedPatternCount: Int { threadFormatters.patterns.count } private static func cachedFormatter(_ pattern: String, _ calendar: Calendar) -> DateFormatter { // A preference-following value can change without a new call-site // value. Keep it live; ordinary Calendar.current is a value snapshot. guard calendar != .autoupdatingCurrent, calendar.timeZone != .autoupdatingCurrent, calendar.locale != .autoupdatingCurrent else { return formatter(pattern, calendar) } let cache = threadFormatters let key = FormatterKey(pattern: pattern, calendar: calendar) if let found = cache.patterns[key] { return found } let made = formatter(pattern, calendar) if cache.patterns.count >= 64 { cache.patterns.removeAll(keepingCapacity: true) } cache.patterns[key] = made return made } /// A label's value, using a private formatter that never leaves this /// thread. The public mutable factory below remains independent. public static func string(_ at: Date, pattern: String, calendar: Calendar = .current) -> String { cachedFormatter(pattern, calendar).string(from: at) } /// The years a real record's day falls in — the core's own bound for a /// mail's date (`mailbox::mail_date::YEARS`). A day outside them is a /// spoiled stamp, never a heading. public static let believableYears = 1900...2100 /// `YYYY-MM-DD` and nothing else. /// /// Hand-written rather than a `Regex` literal because a `Regex` is not /// `Sendable` and this is read from every thread a formatter runs on; /// hand-written rather than `NSRegularExpression` because building one per /// call to parse a ten-character string is absurd. public static func isDayOnly(_ value: String) -> Bool { let scalars = Array(value.utf8) guard scalars.count == 10 else { return false } func digit(_ at: Int) -> Bool { scalars[at] >= 48 && scalars[at] <= 57 } func dash(_ at: Int) -> Bool { scalars[at] == 45 } for at in [0, 1, 2, 3, 5, 6, 8, 9] where !digit(at) { return false } return dash(4) && dash(7) } /// The weekday of a bare day, whole, in `locale`'s own words ("Monday"): /// a list kept to its next day says which day that is. Nil when it is no /// day. public static func weekday(of day: String, locale: Locale = .current, calendar: Calendar = .current) -> String? { guard isDayOnly(day), let date = parse(day, calendar: calendar) else { return nil } return date.formatted(Date.FormatStyle(locale: locale, calendar: calendar, timeZone: calendar.timeZone).weekday(.wide)) } /// The one parsing seam, and the reason it is a seam. /// /// A calendar DAY carries no timezone. `Date("2026-08-08")` — and /// `ISO8601DateFormatter` — read a bare day as UTC midnight, which is /// 7 August for everyone west of Greenwich; the phone's `parseISO` reads it /// as LOCAL midnight, and that is the behaviour a journal page depends on. /// So a bare day is built through the calendar's own components, and /// anything else is a real instant. public static func parse(_ value: String, calendar: Calendar = .current) -> Date? { if isDayOnly(value) { let parts = value.split(separator: "-").compactMap { Int($0) } guard parts.count == 3 else { return nil } var components = DateComponents() components.year = parts[0] components.month = parts[1] components.day = parts[2] guard let built = calendar.date(from: components) else { return nil } // `date(from:)` ROLLS OVER rather than refusing: month 13 becomes // January of the next year and day 45 walks into the following // month, so "2026-13-45" would silently answer 14 Feb 2027. The // phone's `parseISO` refuses it, and a spoiled day must draw // nothing rather than a confident wrong date — so the components // are read back and must be the ones that went in. let back = calendar.dateComponents([.year, .month, .day], from: built) guard back.year == parts[0], back.month == parts[1], back.day == parts[2] else { return nil } return built } if let found = instant(value) { return found } // A ZONELESS STAMP IS LOCAL, NOT NOTHING. `ISO8601DateFormatter` // REQUIRES a zone designator, so "2026-08-08T14:00:00" — which is what // a calendar app's own export writes, and what `new Date(at)` on the // phone reads as 2pm HERE — came back nil and the row printed an empty // string where its time should be. These two patterns are the phone's // fall-through, pinned to the calendar's zone so "local" means the same // thing it means everywhere else in this file. for pattern in ["yyyy-MM-dd'T'HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm"] { if let found = cachedFormatter(pattern, calendar).date(from: value) { return found } } return nil } /// An epoch instant in MILLISECONDS, which is the unit every row in this /// database carries and the one JavaScript hands out. Seconds are what /// `Date(timeIntervalSince1970:)` takes, and passing one for the other is /// wrong by a factor of a thousand with no error — so the unit is in the /// name, and every call site has to say which it meant. public static func parse(millis: Double) -> Date? { guard millis.isFinite else { return nil } return Date(timeIntervalSince1970: millis / 1000) } // MARK: - The wire /// The one instant SHAPE this app writes and every package reads. /// /// `2026-07-16T03:30:00.000Z` — UTC, three fractional digits, `Z`: exactly /// what the crate writes (`crates/cotton-tools/src/clock.rs::iso`, the /// `Date.prototype.toISOString()` shape every row in the file carries), so a /// stamp the phone wrote and a stamp the server wrote are indistinguishable /// and sort as text. **Never `+00:00`, never a local zone**: `ISO8601DateFormatter` /// takes the zone from its `timeZone` property, and the default is GMT only /// by documentation — it is pinned here so a caller cannot inherit a local /// one by accident, which is the bug that put a zoned stamp on one /// screen's write and a zoneless one on a todo. /// /// There used to be five writers with three option sets (a todo's due date /// without milliseconds, a notification's `askedAt` from a bare /// formatter, the calendar pinned to UTC, and two more in whatever zone /// the formatter defaulted to) and four readers, one of /// which accepted only the fractional spelling — so a stamp one screen /// wrote was one another package could not read. `WireDateSweepTests` /// keeps `ISO8601DateFormatter` in this file and nowhere else. public static func format(_ at: Date) -> String { threadFormatters.fractional.string(from: at) } /// An instant as RFC 3339 in `zone`'s own offset /// ("2026-10-05T09:30:00+05:30") — what the core's phrase parser takes as /// `now`, the one form it accepts; `format` writes UTC instants. public static func formatZoned(_ at: Date, zone: TimeZone) -> String { var calendar = Calendar(identifier: .gregorian) calendar.timeZone = zone return string(at, pattern: "yyyy-MM-dd'T'HH:mm:ssxxx", calendar: calendar) } /// An instant with a zone designator, in either spelling. /// /// `ISO8601DateFormatter` will not accept both `…:00.123Z` and `…:00Z` at /// once, so it is asked twice. The plain spelling is READ although it is /// never WRITTEN: an older row, a server-side writer that predates the /// millisecond rule, a stamp typed by hand — refusing those is how a /// an auto-insert "went flaky" and an event lost its time. /// A zoneless stamp or a bare day is NOT an instant: `parse(_:calendar:)` /// reads those, in the calendar the caller is standing in, and nothing /// below it should. /// /// Reused only on this thread: a timeline provider and a view body /// must never share one mutable Foundation formatter instance. public static func instant(_ value: String?) -> Date? { guard let value, !value.isEmpty else { return nil } let cache = threadFormatters if let found = cache.fractional.date(from: value) { return found } return cache.plain.date(from: value) } /// A formatter pinned to the app's own spelling. `en_US_POSIX` is the fixed /// locale every Apple document names for a pattern that must not move. /// Public because `DateFormats` and the screens spell their labels through /// it; the SPELLINGS stay theirs, only the pinning lives here. public static func formatter(_ pattern: String, _ calendar: Calendar) -> DateFormatter { let out = DateFormatter() out.locale = Locale(identifier: "en_US_POSIX") out.calendar = calendar out.timeZone = calendar.timeZone out.dateFormat = pattern return out } }