Search code examples
swifttextformatting

How to get .date style in uppercase?


If I've got this text block

 Text("Logged On: \(theDate, style: .date))")

Is there anything I can do to get the date text converted to all caps? Just adding a

.textCase(.uppercase)

isn't working.


Solution

  • Rather than using the style: parameter, which takes aText.DateStyle, use the format: parameter, which takes a FormatStyle. The latter is much more customisable.

    You can make your own FormatStyle, and pass it to format:

    struct CapitalisedFormatStyle: FormatStyle {
        func format(_ value: Date) -> String {
            // delegate to the built-in date format style
            Date.FormatStyle(date: .long).format(value)
                .localizedUppercase
                // or just .uppercased() if you prefer
        }
    }
    
    // for easy access with just .capitalisedDate
    extension FormatStyle where Self == CapitalisedFormatStyle {
        static var capitalisedDate: CapitalisedFormatStyle { .init() }
    }
    
    Text("Logged On: \(someDate, format: .capitalisedDate)")