John D. John D. - 1 year ago 65
Swift Question

Convert long month name to int

I understand how to use an

to convert a month component into a long name string, but how does one convert a month name to an

I've been using a switch statement to convert, but I'm thinking there must be a simpler way.

For example, I'd like to convert "May" to 5.

Answer Source

Use MM for the month format. Use stringFromDate to convert your NSDate to a String. Then convert your string to an Int with .toInt()

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM"
let monthString = dateFormatter.stringFromDate(NSDate()) // "05"
let monthInt = monthString.toInt() // 5