deepak kumar deepak kumar - 21 days ago 6
Swift Question

How to get month & day in swift?

I want to get the month & date from date as

29 NOV
in Swift. I have tried below code but this does not work me.

func getMonthfromDate(str_date:String)
{
let dateAsString = str_date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "dd-mm"
print("date is \(dateFormatter.string(from: date!))")

}


Input-"19-11-2016"
Output-19:00


Please guide which is right method ?

Answer

Your second formate is wrong it should be dd-MM, mm is for minute also in your question you have told that you want date and month like 29 NOV then your formate should be dd-MMM.

let dateAsString = str_date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
if let date = dateFormatter.date(from: dateAsString) {
    dateFormatter.dateFormat = "dd-MMM"
    print("date is \(dateFormatter.string(from: date))")
}

Note : Do not force wrap date object using ! it will crash your application if it is nil batter to use optional wrapping with if let and guard.

Check this for other date formatters.