parsingJSON(date)到Swift

我在Swift中的应用程序中返回了JSON,并且有一个返回给我的date的字段。 当我提到这个数据时,代码给了我一些像“/ Date(1420420409680)/”。 我如何将其转换成NSDate? 在Swift中,我已经用Objective-Ctesting了一些例子,但没有成功。

这与JSON编码看起来非常相似,在Microsoft和ASP.NET AJAX中使用了date, 在JavaScript和.NET中的JavaScript对象表示法(JSON)简介中对此进行了描述:

例如,微软的ASP.NET AJAX既不使用所描述的约定。 相反,它将.NET DateTime值编码为JSONstring,其中string的内容是/ Date(ticks)/,其中tick表示自epoch(UTC)以来的毫秒数。 因此,1989年11月29日上午4:55:30在UTC中编码为“\ / Date(628318530718)\ /”。

唯一的区别是,你有格式/Date(ticks)/而不是\/Date(ticks)\/

你必须提取括号之间的数字。 除以1000即表示自1970年1月1日以来的秒数。

以下代码显示了如何完成。 它被实现为NSDate的“failable便捷初始值设定程序”

 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 } } } 

示例用法(使用您的datestring):

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

这给出了输出

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

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

例:

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

添加到其他人提供的内容,只需在下面的类中创build实用程序方法:

  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 } 

然后你可以在你成功返回的parsing的JSON对象中调用这个方法,如下所示:

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

或者,您可以完全忽略上面的实用程序方法和调用者代码,只需执行以下操作:

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

这应该工作!

它看起来像一个UNIX时间戳:01/12/2015 @ 6:14 pm(UTC)[根据http://www.unixtimestamp.com/index.php ]

您可以使用构造函数NSDate(timeIntervalSince1970:unixTimestamp)将其转换为NSDate对象

Swift 3.0使用JSONstring转换为date和时间

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

checkInTimewill将是你的String.Hope它将帮助某人