Converting String to NSDate Giving Wrong Date

2019-01-20 19:13发布

问题:

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