New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Date and Time #421
Comments
You may use an extension like below, extension JSON {
public var date: NSDate? {
get {
switch self.type {
case .String:
return Formatter.jsonDateFormatter.dateFromString(self.object as! String)
default:
return nil
}
}
}
public var dateTime: NSDate? {
get {
switch self.type {
case .String:
return Formatter.jsonDateTimeFormatter.dateFromString(self.object as! String)
default:
return nil
}
}
}
} and initialize formatters depending on the data you may receive. class Formatter {
private static var internalJsonDateFormatter: NSDateFormatter?
private static var internalJsonDateTimeFormatter: NSDateFormatter?
static var jsonDateFormatter: NSDateFormatter {
if (internalJsonDateFormatter == nil) {
internalJsonDateFormatter = NSDateFormatter()
internalJsonDateFormatter!.dateFormat = "yyyy-MM-dd"
}
return internalJsonDateFormatter!
}
static var jsonDateTimeFormatter: NSDateFormatter {
if (internalJsonDateTimeFormatter == nil) {
internalJsonDateTimeFormatter = NSDateFormatter()
internalJsonDateTimeFormatter!.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
}
return internalJsonDateTimeFormatter!
}
} |
I like this answer, however I have a question. If the dateFormat I enter in the Formatter class doesn't match the json, will it not return anything? For example, my json date is |
My JSON format is same as yours and here is the format I used: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSSZZ" |
@lmacfadyen Thanks very much, I will give that a try. |
@lmacfadyen That worked. Thanks very much. |
@rmoffett This issue should be closed. |
It would be good to add locale setting on the NSDateFormatter to this, otherwise it may fail depending on device locale. |
Thank you for this nice snippet, it saved me some time. Here is the code updated for Swift3:
|
class Formatter {
static let jsonDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
static let jsonDateTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
return formatter
}()
} |
In iOS 10+ static let jsonDateTimeFormatter: DateFormatter = ISO8601DateFormatter() |
Is there a reason why this is not included? Will a PR be accepted? I am using this with Outlook, and the dateTime doesn't send the milliseconds so the regex above will fail, I need to remove the SSS part and it worked. |
Where is
json["date"].date
orjson["time"].time
?The text was updated successfully, but these errors were encountered: