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.
The data format used for the pattern argument is specified by SimpleDateFormat: @JsonFormat(shape = JsonFormat. Shape. STRING, pattern = "yyyy-MM-dd@HH:mm:ss.
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.
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.
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.
Use the following string format to convert a server string into a Date
dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With