bogen
bogen

Reputation: 10432

Can you use NSDateformatter for creating dates with only month and year?

I have a data source that gives me dates

22017            // means: february 2017
122017           // december 2017
52018            // May 2018

i've tried parsing this with format String Myyyy, which does not get correct dates. I'm now adding a '-' dash before the last 4 letters to correctly separate year and month

5-2018
12-2018 

But the NSDateformatter still does not give the correct format when setting M-yyyy, and i really don't understand why. Is it just too little information to create a date?

Upvotes: 1

Views: 42

Answers (1)

vadian
vadian

Reputation: 285069

It does indeed work, but you have to specify exactly if the month has one or two digits

let dateArray = ["22017", "122017", "52018"]

let dateFormatter = DateFormatter()

for string in dateArray {
    dateFormatter.dateFormat = string.characters.count == 5 ? "Myyyy" : "MMyyyy"
    let date = dateFormatter.date(from: string)
    print(date)
}

Upvotes: 2

Related Questions