Convert NSNumber to NSTimeInterval in Swift

15,768

Solution 1

NSTimeInterval is just a typedaliased Double.

Therefore casting from NSNumber to NSTimeInterval:

let myDouble = NSNumber(double: 1.0)
let myTimeInterval = NSTimeInterval(myDouble.doubleValue)

Edit: And the reverse is true.

let myTimeInterval = NSTimeInterval(1.0)
let myDouble = NSNumber(double: myTimeInterval)

Edit 2: As @DuncanC points out in the comments below, you can cast directly in the method call:

let date = NSDate(timeIntervalSince1970: NSTimeInterval(_matchDateTime))

Solution 2

Try casting your NSNumber to a Double. This code works in a playground:

let aNumber: NSNumber = 1234567.89
let aDate = NSDate(timeIntervalSinceReferenceDate: Double(aNumber))
Share:
15,768
BeingShashi
Author by

BeingShashi

Updated on July 21, 2022

Comments

  • BeingShashi
    BeingShashi almost 2 years

    I'm stuck with some sort of casting in Swift as I am very new to Swift.

    Here is my code:

     if let matchDateTime = item["matchDate"].number {
         _matchDateTime=matchDateTime
     }
    
     println(_matchDateTime)                      
     let date = NSDate(timeIntervalSince1970:_matchDateTime)
    

    but its giving me the error:

    Extra argument timeSinceInterval1970 in call
    

    I don't know whats that error, may be convert NSNumber to NSTimeInterval but how? No idea.

    Anyone who can help me out with this.

    Thanks in advance.