Swift date formatting

牧云@^-^@ 提交于 2020-01-28 10:41:28

问题


I'm trying to pull a date string from a button and format is as a date to be store in CoreData.

Here is my code:

let dateStr = setDateBTN.titleLabel?.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-YYYY"
let date:NSDate = dateFormatter.dateFromString(dateStr!)!

If I do a println on dateStr I get the following: 03-10-2015. Then if I immediately println on date I get: 2014-12-21 05:00:00 +0000.

Any ideas as to why the actual date is changing when I run it through the date formatter?


回答1:


NSDateFormatter Class Reference : http://goo.gl/7fp9gl

Date Formatting Guide (Apple) : http://goo.gl/8zRTQl

A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar.

Your code should work, as you expect, like this :

let dateStr = setDateBTN.titleLabel?.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date:NSDate = dateFormatter.dateFromString(dateStr!)!


来源:https://stackoverflow.com/questions/28901921/swift-date-formatting

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