Convert Date to Integer in Swift

2019-02-12 10:00发布

I am updating some of my old Swift 2 answers to Swift 3. My answer to this question, though, is not easy to update since the question specifically asks for NSDate and not Date. So I am creating a new version of that question that I can update my answer for.

Question

If I start with a Date instance like this

let someDate = Date()

how would I convert that to an integer?

Related but different

These questions are asking different things:

1条回答
虎瘦雄心在
2楼-- · 2019-02-12 10:28

Date to Int

// using current date and time as an example
let someDate = Date()

// convert Date to TimeInterval (typealias for Double)
let timeInterval = someDate.timeIntervalSince1970

// convert to Integer
let myInt = Int(timeInterval)

Doing the Double to Int conversion causes the milliseconds to be lost. If you need the milliseconds then multiply by 1000 before converting to Int.

Int to Date

Including the reverse for completeness.

// convert Int to Double
let timeInterval = Double(myInt)

// create NSDate from Double (NSTimeInterval)
let myNSDate = Date(timeIntervalSince1970: timeInterval)

I could have also used timeIntervalSinceReferenceDate instead of timeIntervalSince1970 as long as I was consistent. This is assuming that the time interval is in seconds. Note that Java uses milliseconds.

Note

  • For the old Swift 2 syntax with NSDate, see this answer.
查看更多
登录 后发表回答