Formatting date with Swift

泄露秘密 提交于 2019-12-31 03:29:07

问题


I am trying to Convert a String into Date using Date Formatter .

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd’T’HH:mm:ss’Z’"
var AvailabletoDateTime = dateFormatter.dateFromString("2015-07-16’T’08:00:00’Z’")

But the AvailabletoDateTime is Returning nil . Can Someone please Help me ,and let me know if i miss Anything Here .


回答1:


Try like this:

let dateFormatter = NSDateFormatter()
dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let availabletoDateTime = dateFormatter.dateFromString("2015-07-16T08:00:00Z")



回答2:


This looks like you're trying to use an ISO 8601/RFC 3339 date. Usually the date string will not include any quotes. It will be: something like 2015-07-16T08:00:00Z. FYI, the Z stands for GMT/UTC timezone (as opposed to your local timezone).

So, in Swift 3:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.locale = Locale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let availabletoDateTime = dateFormatter.date(from: "2015-07-16T08:00:00Z")

Note, I'm (a) using ZZZZZ rather than Z in my format string; and (b) explicitly setting the timeZone. I do this for my formatter can not only successfully parse the string 2015-07-16T08:00:00Z into a Date object, but that it can also be used to go the other direction, converting a Date object into a string in the format like 2015-07-16T08:00:00Z.

Also note I'm using ' character, not the character. Nor do I need to set the calendar, as locale of en_US_POSIX is all you need.

For more information, see Technical Q&A 1480.


Not, nowadays you'd use the new ISO8601DateFormatter:

let dateFormatter = ISO8601DateFormatter()
let availabletoDateTime = dateFormatter.date(from: "2015-07-16T08:00:00Z")

In Swift 3, use this ISO8601DateFormatter, if you can, but recognize that it doesn't provide as much control (e.g. prior to iOS 11, you couldn't specify milliseconds). But in this case, it's sufficient.

For Swift 2 rendition, see previous revision of this answer.



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

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