Reputation: 157
I am trying to convert a date in which the javascript code is generating the current date using the Date() function. But when I print it out, I am getting nil.
my code:
let date2 = data?[0] as! String
println(date2)
var str = "2013-07-21T19:32:00Z"
var dateFor: NSDateFormatter = NSDateFormatter()
dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
var Date: NSDate? = dateFor.dateFromString(date2)
println(Date)
date2 => is printing out 2015-05-15T21:58:00.066Z Date => is printing nil str is just for testing and works perfectly.
Anyone see any flaws in the code?
Upvotes: 3
Views: 6242
Reputation: 2135
Use ISO8601DateFormatter
per documentation going forward
In macOS 10.12 and later or iOS 10 and later, use the ISO8601DateFormatter class when working with ISO 8601 date representations.
import Foundation
let isoStr = "2020-02-18T11:40:01.000Z"
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
isoDateFormatter.formatOptions = [
.withFullDate,
.withFullTime,
.withDashSeparatorInDate,
.withFractionalSeconds]
if let isoDateFormatted = isoDateFormatter.date(from: isoStr) {
print(isoDateFormatted)
}
Upvotes: 1
Reputation: 236370
The issue is that str
and date2
two are not the same date format. str
format is "yyyy-MM-dd'T'HH:mm:ssZ"
while date2
format is "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
. Besides that you should always set your dateFormatter's locale to "en_US_POSIX"
when parsing fixed-format dates:
let date2 = "2015-05-15T21:58:00.066Z"
let dateFormatter = DateFormatter()
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: date2) {
print(date) // "2015-05-15 21:58:00 +0000"
}
Upvotes: 19
Reputation: 4739
Swift 4+
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let str = "2013-07-21T19:32:00Z"
if let date = dateFormatter.date(from: str) {
print(date)
}
Output: 2013-07-21 19:32:00 +0000
Upvotes: 0