我已将UIDatepicker附加到名为dateField的文本字段。当用户点击该字段时,弹出UIDatePicker并且用户选择出生日期。该日期作为一个字符串保存到该dateField中,并根据用户位置显示格式,即1990年5月4日在美国或1990年5月4日在澳大利亚。Swift - 将日期字符串从“datepicker填充日期字段”转换为nsdate
后来当他们按下保存按钮时,我想将日期保存到CoreData。我一直试图将日期字符串转换回NSDate,但我不断遇到问题并得到一个无日期。
我相信在做这件事之前需要设置NSDateFormatter语言环境和时区,因此我将它设置为用户的currentLocale和localTimeZone。我也相信我需要设置日期格式...如果我将日期格式设置为“dd MMM yyyy”,如果用户区域设置为澳大利亚,NSDate将起作用,但如果将区域设置设置为美国,则不会。
如何设置日期格式,以便它允许dateFromString方法工作,而不管用户的区域设置如何。或者我应该有不同的做这个(即出生日期保存为一个字符串,而不是时间的NSDate的独特之处)
我的代码
let dateStr = "20 Aug 1990" //suppose dateField contains this string as saved from a UIDatePicker (formatted according to the user's locale ... ie would be Aug 20 1990 in USA locale)
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.timeZone = NSTimeZone.localTimeZone()
formatter.dateFormat = "dd MMM yyyy" //how can i set this to be non-locale specific
var dobStr = dobField.text
var dob: NSDate? = formatter.dateFromString(dobStr)
println(dob) //prints nil if user locale is USA