I'm trying to get a record from MongoDB which has a DateTime property. This property is ISODate but is received as a long data type (milliseconds since 1970) through the Perfect-MongoDB API.
The code looks like this:
if var something = dictionary["Something"] as? [String:Any], var intDate = something["$date"] as? Int64
{
let date = Date(timeIntervalSince1970: TimeInterval(intDate/1000))
}
This code is working fine in Mac OSX. However in Linux, created["$date"] as? Int64
is always nil
.
I've tried a couple of things, including using Double
and NSNumber
instead of Int64 but it is still nil
.
Any ideas on how I can access this number? I need to convert it to a readable date, and the way I'm doing this is through TimeInterval()
which needs a Double value for seconds after 1970, so it needs to be divisible by 1000 and convertible to Double during that step.
Edit: This is the NSNumber code where intDate
is still nil
and thus doesn't fall through the let date
line. something
is not nil
if var something = dictionary["Something"] as? [String:Any], var intDate = something["$date"] as? NSNumber
{
let date = Date(timeIntervalSince1970: TimeInterval(NSDecimalNumber(decimal:intDate.decimalValue/1000).doubleValue))
}
Edit 2: Sample Dictionary for this case:
var dictionary : [String:Any] = ["SomethingElse":"SomeOtherData","Something":["$date": 1507710414599]]
Apparently there is only limited conversion between integer types and NSNumber
in Swift on Linux, so you have to cast to the exact type,
which is Int
in this case:
let dictionary : [String: Any] = ["SomethingElse":"SomeOtherData","Something":["$date": 1507710414599]]
if let something = dictionary["Something"] as? [String:Any],
let numDate = something["$date"] as? Int {
let date = Date(timeIntervalSince1970: Double(numDate)/1000)
print("Date:", date)
}