Skip to content

Date.FormatStyle not behaving as expected when init with nils and a suggestion to improve it #1434

@malhal

Description

@malhal

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:

/// - 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions