Converting String to NSDate Giving Wrong Date

白昼怎懂夜的黑 提交于 2019-12-29 02:06:32

问题


I have a String that I converted using stringFromDate and now I'm trying to convert it back, however when the UIPicker starts, it's giving me the wrong day

 let dateFormatter = NSDateFormatter()
 dateFormatter.dateFormat = "dd MMM YYYY"

 print(birthday) // logs 15 Jan 1992

 let date = dateFormatter.dateFromString(birthday)
 self.datePicker.setDate(date!, animated: true)

I tried hardcoding "15 Feb 1992" but still the same result. The date on UIDatePicker shows 22 Dec 1991 on Start.

If I use hardcore 10 Jan 1980, it starts from 23 December 1979.

(I don't know if that's the case but I have MMM dd YYYY in UIPickerView whereas it's dd MMM YYYY for the strings.. I don't think though because while saving, it saves the right value)..


回答1:


You are using the wrong format. You need dd MMM yyyy.




回答2:


To use correct format string is most important..

YYYY is week-based calendar year. (used in ISO week-year calendar)

yyyy is ordinary calendar year.

so, You should use 'yyyy' instead of 'YYYY'.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"

print(birthday)  

let date = dateFormatter.dateFromString(birthday)
self.datePicker.setDate(date!, animated: true)

For more string format for Date: refer this link

https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx



来源:https://stackoverflow.com/questions/36894791/converting-string-to-nsdate-giving-wrong-date

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