Search code examples
swiftcocoa-touchnsdatensdateformatterdate-parsing

Convert long month name to int


I understand how to use an NSDateFormatter to convert a month component into a long name string, but how does one convert a month name to an int?

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.


Solution

  • 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