在Swift中将Date转换为Integer

时间:2022-11-22 02:33:45

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.

我正在更新Swift 3的一些旧的Swift 2答案。但是,我对这个问题的回答并不容易更新,因为问题特别要求NSDate而不是Date。所以我正在创建该问题的新版本,我可以更新我的答案。

Question

If I start with a Date instance like this

如果我从这样的Date实例开始

let someDate = Date()

how would I convert that to an integer?

我该如何将其转换为整数?

Related but different

相关但不同

These questions are asking different things:

这些问题提出了不同的问题:

1 个解决方案

#1


43  

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.

执行Double to Int转换会导致毫秒丢失。如果需要毫秒,则在转换为Int之前乘以1000。

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.

只要我保持一致,我也可以使用timeIntervalSinceReferenceDate而不是timeIntervalSince1970。这假设时间间隔以秒为单位。请注意,Java使用毫秒。

Note

  • For the old Swift 2 syntax with NSDate, see this answer.
  • 对于使用NSDate的旧Swift 2语法,请参阅此答案。

#1


43  

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.

执行Double to Int转换会导致毫秒丢失。如果需要毫秒,则在转换为Int之前乘以1000。

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.

只要我保持一致,我也可以使用timeIntervalSinceReferenceDate而不是timeIntervalSince1970。这假设时间间隔以秒为单位。请注意,Java使用毫秒。

Note

  • For the old Swift 2 syntax with NSDate, see this answer.
  • 对于使用NSDate的旧Swift 2语法,请参阅此答案。