JSON parsing (date) in Swift

I have returned JSON in my application in Swift, and I have a field that returns the date to me. When I refer to this data, the code gives me something like "/ Date (1420420409680) /". How to convert this to NSDate? In Swift, please, I tested the examples with Objective-C, without success.

+6
source share
4 answers

This is very similar to the JSON encoding for the date used by Microsoft ASP.NET AJAX, which is described in Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET :

For example, Microsoft ASP.NET AJAX does not use any of the conventions described. Rather, it encodes .NET DateTime values ​​as a JSON string, where the content of the string is / Date (ticks) / and where ticks represent milliseconds from the era (UTC). So, on November 29, 1989, 4:55:30, in UTC it is encoded as "\ / Date (628318530718) \ /".

The only difference is that you have the format of /Date(ticks)/ and not \/Date(ticks)\/ .

You need to extract the number between parentheses. Dividing this by 1000 gives the number in seconds since January 1, 1970.

The following code shows how to do this. It is implemented as a "failed convenience initializer" for NSDate :

 extension NSDate { convenience init?(jsonDate: String) { let prefix = "/Date(" let suffix = ")/" // Check for correct format: if jsonDate.hasPrefix(prefix) && jsonDate.hasSuffix(suffix) { // Extract the number as a string: let from = jsonDate.startIndex.advancedBy(prefix.characters.count) let to = jsonDate.endIndex.advancedBy(-suffix.characters.count) // Convert milliseconds to double guard let milliSeconds = Double(jsonDate[from ..< to]) else { return nil } // Create NSDate with this UNIX timestamp self.init(timeIntervalSince1970: milliSeconds/1000.0) } else { return nil } } } 

Usage example (with your date string):

 if let theDate = NSDate(jsonDate: "/Date(1420420409680)/") { print(theDate) } else { print("wrong format") } 

It gives a way out

  2015-01-05 01:13:29 +0000

Update for Swift 3 (Xcode 8):

 extension Date { init?(jsonDate: String) { let prefix = "/Date(" let suffix = ")/" // Check for correct format: guard jsonDate.hasPrefix(prefix) && jsonDate.hasSuffix(suffix) else { return nil } // Extract the number as a string: let from = jsonDate.index(jsonDate.startIndex, offsetBy: prefix.characters.count) let to = jsonDate.index(jsonDate.endIndex, offsetBy: -suffix.characters.count) // Convert milliseconds to double guard let milliSeconds = Double(jsonDate[from ..< to]) else { return nil } // Create NSDate with this UNIX timestamp self.init(timeIntervalSince1970: milliSeconds/1000.0) } } 

Example:

 if let theDate = Date(jsonDate: "/Date(1420420409680)/") { print(theDate) } else { print("wrong format") } 
+9
source

Adding to what others have provided, just create a utility method in your class below:

  func dateFromStringConverter(date: String)-> NSDate? { //Create Date Formatter let dateFormatter = NSDateFormatter() //Specify Format of String to Parse dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" //or you can use "yyyy-MM-dd'T'HH:mm:ssX" //Parse into NSDate let dateFromString : NSDate = dateFormatter.dateFromString(date)! return dateFromString } 

You can then call this method on your successfully returned, parsed JSON object, as shown below:

 //Parse the date guard let datePhotoWasTaken = itemDictionary["date_taken"] as? String else {return} YourClassModel.dateTakenProperty = self.dateFromStringConverter(datePhotoWasTaken) 

Or you can completely ignore the utility method and caller code and just do it:

 //Parse the date guard let datePhotoWasTaken = itemDictionary["date_taken"] as? NSString else {return} YourClassModel.dateTakenProperty = NSDate(timeIntervalSince1970: datePhotoWasTaken.doubleValue) 

And that should work!

+2
source

Looks like a UNIX timestamp: 12/01/2015 @ 6: 14 pm (UTC) [According to http://www.unixtimestamp.com/index.php ]

You can convert it to an NSDate object using the NSDate constructor (timeIntervalSince1970: unixTimestamp)

+1
source

Convert JSON String by date and time in Swift 3.0 Use the code below: -

 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

0
source

Source: https://habr.com/ru/post/980880/


All Articles