Format a date but without the year

I want to display the long version of a date BUT WITHOUT the year


With:

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
dateFormatter.doesRelativeDateFormatting = true
dateFormatter.locale = Calendar.current.locale

if let inPast = Calendar.current.date(byAdding: .day, value: -30, to: Date()) {
    let text = dateFormatter.string(from: inPast)
}


The output is "Wednesday, April 15, 2020" and I want to have "Wednesday, April 15"

Answered by Claude31 in 420448022

Sure, so see the other option in my post.


Or use a fixed format

    dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMMM dd") 
    print(dateFormatter.string(from: inPast)) // Wednesday, April 15

A simple trick would be to suppress the last 6 chars:


let text = dateFormatter.string(from: inPast)..dropLast(6)


Or use a cfixed format

    dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMMM dd")
    print(dateFormatter.string(from: inPast)) // Wednesday, April 15

I'm not sure this will work in all language / region

Accepted Answer

Sure, so see the other option in my post.


Or use a fixed format

    dateFormatter.setLocalizedDateFormatFromTemplate("EEEE, MMMM dd") 
    print(dateFormatter.string(from: inPast)) // Wednesday, April 15

Do you have a kink to full documentation of setLocalizedDateFormatFromTemplate? I haven't found it already.

Is it possible that when you set a custom date format you lose the relative formatting?
Format a date but without the year
 
 
Q