简体   繁体   English

将字符串转换为 NSDate 给出错误的日期

[英]Converting String to NSDate Giving Wrong Date

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我有一个使用stringFromDate转换的字符串,现在我试图将它转换回来,但是当 UIPicker 启动时,它给了我错误的一天

 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.我尝试硬编码"15 Feb 1992"但结果仍然相同。 The date on UIDatePicker shows 22 Dec 1991 on Start. UIDatePicker 上的日期在 Start 上显示为 1991 年 12 月 22 日。

If I use hardcore 10 Jan 1980 , it starts from 23 December 1979.如果我使用 hardcore 10 Jan 1980 ,则从 1979 年 12 月 23 日开始。

(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).. (我不知道是不是这种情况,但我在 UIPickerView 中有MMM dd YYYY而它是字符串的dd MMM YYYY .. 我不这么认为,因为在保存时,它保存了正确的值)。

You are using the wrong format.您正在使用错误的格式。 You need dd MMM yyyy .你需要dd MMM yyyy

To use correct format string is most important..使用正确的格式字符串是最重要的..

YYYY is week-based calendar year. YYYY 是基于周的日历年。 (used in ISO week-year calendar) (用于 ISO 周年日历)

yyyy is ordinary calendar year. yyyy 是普通日历年。

so, You should use 'yyyy' instead of 'YYYY'.所以,你应该使用'yyyy'而不是'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://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM