-
Notifications
You must be signed in to change notification settings - Fork 202
Description
When Date.FormatStyle
is init with nils for date and time styles, an empty string is not returned like the note in the code comment below states:
swift-foundation/Sources/FoundationInternationalization/Formatting/Date/DateFormatStyle.swift
Lines 262 to 263 in 94a9456
/// - Note: Always specify the date style, time style, or the date components to be included in the formatted string with the symbol modifiers. Otherwise, an empty string will be returned when you use the instance to format a `Date`. | |
public init(date: DateStyle? = nil, time: TimeStyle? = nil, locale: Locale = .autoupdatingCurrent, calendar: Calendar = .autoupdatingCurrent, timeZone: TimeZone = .autoupdatingCurrent, capitalizationContext: FormatStyleCapitalizationContext = .unknown) { |
Example:
let defaultStyle = Date.FormatStyle()
defaultStyle.format(Date())
Expected output: ""
Actual output: "15/07/2025, 13:34"
let nilStyle = Date.FormatStyle(date: nil, time: nil)
nilStyle.format(Date())
Expected output: ""
Actual output: "15/07/2025, 13:34"
I discovered this when I was trying to format a date without the time and I failed with:
let onlyDate = Date.FormatStyle(time: .omitted)
onlyDate.format(Date())
Expected output: "15/07/2025"
Actual output: "15/07/2025, 13:34"
It seems .omitted
only works if non-nil values for date and time are provided. It appears that date is defaulting to .numeric
when it is not specified how about formalising this in the init? e.g.
public init(..., time: TimeStyle = .numeric, ...
(if that is not coming from my system preferences!)
And then rely on .omitted
as the nil case.
Environment
Swift Playground
Xcode 16.4
macOS 15.5