Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 356
John D. Avatar asked Sep 21 '25 10:09

John D.


2 Answers

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
}
like image 103
Leo Dabus Avatar answered Sep 23 '25 03:09

Leo Dabus


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
like image 44
John D. Avatar answered Sep 23 '25 02:09

John D.