How do I format JSON Date String with Swift?

2019-02-03 07:37发布

问题:

I make an http get request to a server and get back a json object with a date string like this:

{
    name = "Place1";
    temperature = 79;
    humidity = 68;
    reported_at = "2013-07-21T19:32:00Z";
}

I want to format the reported_at key so I can display a readable date and time to the user.

This is the swift code I am trying which keeps returning nil, as it cannot format the date.

    var str = "2013-07-21T19:32:00Z"

    var dateFor: NSDateFormatter = NSDateFormatter()
    dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SSS"

    var yourDate: NSDate? = dateFor.dateFromString(str)

    println(yourDate)

How can I format this date and time with Swift correctly? I want to display the date and time to the user so they can know when the reading was taken.

回答1:

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

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


回答2:

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)
    


回答3:

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


回答4:

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



回答5:

For Converting JSON String to Date & Time in Swift 3.0 Use Below Code:-

    let timeinterval : TimeInterval = (checkInTime as! NSString).doubleValue
    let dateFromServer = NSDate(timeIntervalSince1970:timeinterval)
    print(dateFromServer)
    let dateFormater : DateFormatter = DateFormatter()
    //dateFormater.dateFormat = "dd-MMM-yyyy HH:mm a"  // 22-Sep-2017 14:53 PM
    dateFormater.dateFormat = "dd-MMM-yyyy hh:mm a"   // 22-Sep-2017 02:53 PM
    print(dateFormater.string(from: dateFromServer as Date))

where checkInTimewill be your String.Hope it will help someone