温馨提示:本文翻译自stackoverflow.com,查看原文请点击:swift - Convert long month name to int
cocoa-touch nsdate swift nsdateformatter date-parsing

swift - 将长月名称转换为int

发布于 2020-04-12 09:47:39

我知道如何使用NSDateFormatter将月份成分转换为长名称字符串,但是如何将月份名称转换为int

我一直在使用switch语句进行转换,但是我认为必须有一种更简单的方法。

例如,我想将“ May”转换为5。

查看更多

提问者
John D.
被浏览
11
Daniel Storm 2015-05-26 08:53

使用MM该月的格式。使用stringFromDate你转换NSDate到一个String然后你的字符串转换为一个Int.toInt()

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