Convert string with ordinal format to date on iOS

拟墨画扇 提交于 2019-12-13 22:25:44

问题


Possible Duplicate:
Converting a string to an NSDate


I have date in string and want to convert in NSDate. In string date is:

"21st June 2012"

How can I convert this in NSDate?

Please concentrate on day "21st" not "21" when you give answer.


回答1:


You can use NSDateFormatter to change NSString to NSDate.




回答2:


There is a generic answer for this kind of questions available on Stack Overflow, it's to use NSDateFormatter in Objective-C / DateFormatter in Swift. And the format is following tr35-19 or newer according to Use Format Strings to Specify Custom Formats.

But to deal with your variation of a date format, here is the Swift answer for your specific requirements:

// Your example
let dateString = "21st June 2012"

// Sanitizing input for 2nd, 3rd, 4th
let normalizedDateString = dateString.replacingOccurrences(of: "nd", with: "st").replacingOccurrences(of: "rd", with: "st").replacingOccurrences(of: "th", with: "st")

// Converting string to date object
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "d'st' MMMM yyyy"
let date = formatter.date(from: normalizedDateString)

Same logic in Objective-C.



来源:https://stackoverflow.com/questions/14600914/convert-string-with-ordinal-format-to-date-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!