我正在尝试向JSONSerializable
字段添加特殊dateTaken
方法,因此我想扩展Date
。但我发现Date
是一个结构,不能扩展,所以NSDate
。但我无法弄清楚如何从DateTaken
Date
class DateTaken : NSDate, JSONRepresentable {
static var formatter = DateFormatter()
var JSONRepresentation: AnyObject {
DateTaken.formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" // ISO8601
DateTaken.formatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
return DateTaken.formatter.string(from:self as Date) as AnyObject
}
var JSONLocalTimeRepresentation: AnyObject {
DateTaken.formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return DateTaken.formatter.string(from:self as Date) as AnyObject
}
}
let d = Date()
let dateTaken : DateTaken = DateTaken.init(timeInterval: 0, since: d)
// exception
(lldb) p NSDate.init(timeInterval: 0, since: dateTaken)
(NSDate) $R0 = 0x0000000156e6fdb0 2014-10-13 08:49:18 UTC
(lldb) p dateTaken.init(timeInterval: 0, since: dateTaken)
error: <EXPR>:3:1: error: 'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type
dateTaken.init(timeInterval: 0, since: dateTaken)
^
type(of: )
答案 0 :(得分:0)
这不是Java。我们有扩展。
extension NSDate: JSONRepresentable {
static var formatter = DateFormatter()
var JSONRepresentation: AnyObject {
DateTaken.formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" // ISO8601
DateTaken.formatter.timeZone = TimeZone(abbreviation: "UTC")
return DateTaken.formatter.string(from: self as Date) as AnyObject
}
var JSONLocalTimeRepresentation: AnyObject {
DateTaken.formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return DateTaken.formatter.string(from: self as Date) as AnyObject
}
}
我还怀疑由于共享formatter
而导致此错误。在timeZone
中首次设置JSONRepresentation
后,JSONLocalTimeRepresentation
将像JSONRepresentation
一样。我可能错了,但我现在无法测试。值得一试。