Joh*_* D. 3 cocoa-touch nsdate nsdateformatter date-parsing swift
我知道如何使用a NSDateFormatter将月份组件转换为长名称字符串,但如何将月份名称转换为int?
我一直在使用switch语句来转换,但我认为必须有一个更简单的方法.
例如,我想将"May"转换为5.
您可以使用DateFormatter自定义格式"LLLL"来解析日期字符串(月).如果您只是用英语解析日期,则应将日期格式化程序区域设置为"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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2874 次 |
| 最近记录: |