Convert long month name to int

I understand how to use NSDateFormatter

to convert month component to long name string, but how to convert month name to int

?

I am using a switch statement for the conversion, but I think there should be an easier way.

For example, I would like to convert "May" to 5.

+3


source to share


4 answers


Use MM

for month format. Use stringFromDate

to convert NSDate

to String

. Then convert the string to Int

with.toInt()



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

      

0


source


The custom DateFormatter "LLLL"

can be used to parse a date (month) string. If you are only looking for dates in English, you should set the date 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
}

      

+5


source


Thanks to 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

      

+3


source


NSDateFormatter

has a 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

      

+1


source







All Articles