user1669730
user1669730

Reputation: 65

Formatting date with Swift

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 .

Upvotes: 2

Views: 4768

Answers (2)

Rob
Rob

Reputation: 437372

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.

Upvotes: 5

Leo Dabus
Leo Dabus

Reputation: 236260

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")

Upvotes: 2

Related Questions