Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format JSON Date String with Swift?

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.

like image 868
Nearpoint Avatar asked Feb 26 '15 16:02

Nearpoint


People also ask

How do I set date format in JSON?

The data format used for the pattern argument is specified by SimpleDateFormat: @JsonFormat(shape = JsonFormat. Shape. STRING, pattern = "yyyy-MM-dd@HH:mm:ss.

Does JSON support date format?

JSON does not directly support the date format and it stores it as String. However, as you have learned by now that mongo shell is a JavaScript interpreter and so in order to represent dates in JavaScript, JSON uses a specific string format ISODate to encode dates as string.

What is Swifty JSON in Swift?

SwiftyJSON is a library that helps to read and process JSON data from an API/Server. So why use SwiftyJSON? Swift by nature is strict about data types and wants the user to explicitly declare it. This becomes a problem as JSON data is usually implicit about data types.

Can JSON be a date?

JSON Dates are not dates – they are Strings You can represent strings, numbers, Booleans and even objects, arrays and RegEx expressions with language specific literals, but there's no equivalent literal representation for dates.


4 Answers

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

dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
like image 113
Zell B. Avatar answered Oct 16 '22 23:10

Zell B.


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)
    
like image 36
vadian Avatar answered Oct 16 '22 23:10

vadian


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()
like image 4
Marchy Avatar answered Oct 17 '22 00:10

Marchy


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

like image 1
Changnam Hong Avatar answered Oct 16 '22 23:10

Changnam Hong