Warm tip: This article is reproduced from stackoverflow.com, please click
cocoa-touch nsdate swift nsdateformatter date-parsing

Convert long month name to int

发布于 2020-04-11 22:20:13

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.

Questioner
John D.
Viewed
16
Daniel Storm 2015-05-26 08:53

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