ADB
ADB

Reputation: 719

How to format DateComponents as a partial date string?

I have a DateComponents object that contains a month and a year and I'd like to have a formatted string from it in the style 'March 2021'. I've tried DateComponentsFormatter but none of the properties get anywhere near what I'd like to see.

let components = DateComponents(calendar: .current, timeZone: .current, year: 2021, month: 3, day: nil)
let formatter = DateComponentsFormatter()
let string = formatter.string(from: components) // Optional("2,021y 3mo")

Is this possible to do from DateComponents please?

Upvotes: 2

Views: 2661

Answers (1)

Vollan
Vollan

Reputation: 1915

let date = Calendar.current.date(from: DateComponents())
var formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
print(formatter.string(from: date))

It's pretty much something like this you need to do

let components = DateComponents(calendar: .current, timeZone: .current, year: 2021, month: 3, day: nil)
let date = calendar.current.date(from: components)
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
let string = formatter.string(from: date)

https://nsdateformatter.com/ here you can see how to format the dates in different ways.

Upvotes: 3

Related Questions