How do I format JSON Date String with Swift?

Here is my answer using extension in Swift4.

extension String {
  func toDate(dateFormat: String) -> Date? {

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat

    let date: Date? = dateFormatter.date(from: self)
    return date
}

Simple Usage

let str = "2013-07-21T19:32:00Z";
let dateStr = str.toDate(dateFormat: "yyyy-MM-dd'T'HH:mm:ssZ")

Also, Check dateFormat that you want from here. ISO 8601


Nowadays (September 2017) in Swift 4 there are smarter ways to decode ISO8601:

  • ISO8601DateFormatter

    let str = "2013-07-21T19:32:00Z"
    let formatter = ISO8601DateFormatter()
    let yourDate = formatter.date(from: str)
    
  • JSONDecoder

    struct Place : Decodable {
    
        let name : String
        let temperature : Int
        let humidity : Int
        let reportedAt : Date
    
    }
    
    let json = """
    {"name" : "Place1", "temperature" : 79, "humidity" : 68, "reported_at" : "2013-07-21T19:32:00Z"}
    """
    let data = Data(json.utf8)
    
    let decoder =  JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let place = try! decoder.decode(Place.self, from: data)
    

If you are using SwiftDate (you probably should!) simply use:

Serialize:

let date:NSDate = ....
let dateInRegion = DateInRegion( absoluteTime: date )
let serializedString:String = dateInRegin.toString( .ISO8601Format( .Full ))!

Deserialize:

let serializedDate:String = "2016-03-01T22:10:55.200Z"
let date:NSDate? = serializedDate.toDateFromISO8601()

Use the following string format to convert a server string into a Date

dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"