Home > Mobile >  Swift: iOS 15 date formatter to convert date to a custom string
Swift: iOS 15 date formatter to convert date to a custom string

Time:06-20

I'm trying to convert a date to a string using iOS 15 style formatter like this:

let date = Date()
let formattedDate = date.formatted(
            .dateTime
            .month(.twoDigits)
            .day()
            .year()
)

The Date (as printed in the console) is

"2022-06-19 16:42:56  0000"

How can I build the following string:

"2022 ** 06 ** 19"

out of this date object, using the new iOS 15 date formatter?

CodePudding user response:

You would have to construct a verbatim format style, such as this:

    let date = Date()
    let formatString : Date.FormatString = """
        \(year: .defaultDigits) ** \
        \(month: .twoDigits) ** \
        \(day: .twoDigits)
        """
    let format = Date.VerbatimFormatStyle(
        format: formatString,
        locale: .autoupdatingCurrent,
        timeZone: .autoupdatingCurrent,
        calendar: .init(identifier:.gregorian)
    )
    let s = date.formatted(format) // 2022 ** 06 ** 19
  • Related