4

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
John D.
  • 548
  • 7
  • 19
  • 1
    The correct procedure is here: [Get month number from month name](http://stackoverflow.com/q/9114829), though it's written in ObjC. – jscs May 25 '15 at 23:03

4 Answers4

9

You can use DateFormatter custom format "LLLL" to parse your date string (Month). If you are only parsing dates in english you should set the date formatter locale to "en_US_POSIX":

let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "LLLL"  // if you need 3 letter month just use "LLL"
if let date = df.date(from: "May") {
    let month = Calendar.current.component(.month, from: date)
    print(month)  // 5
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
3

Thanks Josh. I've converted the Obj-C code and posted it below for future reference:

let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let components = NSDateComponents()
let formatter = NSDateFormatter()
formatter.dateFormat = "MMMM"
let aDate = formatter.dateFromString("May")
let components1 = calendar!.components(.CalendarUnitMonth , fromDate: aDate!)
let monthInt = components.month
John D.
  • 548
  • 7
  • 19
1

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
Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
1

NSDateFormatter has monthSymbols property. Try:

let formatter = NSDateFormatter()
formatter.calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)

let monthString = "September"
let month = find(formatter.monthSymbols as! [String], monthString).map { $0 + 1 }
// -> Optional(9)

let monthString2 = "Foobar"
let month2 = find(formatter.monthSymbols as! [String], monthString2).map { $0 + 1 }
// -> nil
rintaro
  • 51,423
  • 14
  • 131
  • 139