问题描述
我正在寻找一种 Swifty 方式来生成时间戳.
I am looking for a Swifty way to generate a timestamp.
我的 macOS 应用程序会记录一些数据并在数据创建时间上打上标记.然后,数据将通过网络发送(作为 Data)在 iPad 上重建.
My macOS app logs some data and stamps it with the time the data was created. The data will then be sent across the network (as Data) to be reconstructed on an iPad.
是否有任何 Swift 类可以生成时间戳?国安日期?NSTimeIntervalSince1970?CFAbsoluteTimeGetCurrent()
Is there any Swift class that will work to generate the timestamp? NSDate? NSTimeIntervalSince1970? CFAbsoluteTimeGetCurrent()
要求是:
- 将时间戳存储在尽可能少的字节中(pref. Int)
- 与真实的地球时间有些相似(我宁愿不生成我的自己的时间格式)
- 毫秒精度
- 快速构建
- iOS 9+、macOS 10.10+
推荐答案
您可以发送您的 Date 并将其转换为 Data(8 字节浮点)并返回日期如下:
You can send your Date converting it to Data (8-bytes floating point) and back to Date as follow:
extension Numeric { var data: Data { var source = self return .init(bytes: &source, count: MemoryLayout<Self>.size) } init<D: DataProtocol>(_ data: D) { var value: Self = .zero let size = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} ) assert(size == MemoryLayout.size(ofValue: value)) self = value } }
<小时>
extension UInt64 { var bitPattern: Double { .init(bitPattern: self) } }
<小时>
extension Date { var data: Data { timeIntervalSinceReferenceDate.bitPattern.littleEndian.data } init<D: DataProtocol>(data: D) { self.init(timeIntervalSinceReferenceDate: data.timeIntervalSinceReferenceDate) } }
<小时>
extension DataProtocol { func value<N: Numeric>() -> N { .init(self) } var uint64: UInt64 { value() } var timeIntervalSinceReferenceDate: TimeInterval { uint64.littleEndian.bitPattern } var date: Date { .init(data: self) } }
<小时>
游乐场测试
Playground Testing
let date = Date() // "Nov 15, 2019 at 12:13 PM" let data = date.data // 8 bytes print(Array(data)) // "[25, 232, 158, 22, 124, 191, 193, 65] " let loadedDate = data.date // "Nov 15, 2019 at 12:13 PM" print(date == loadedDate) // "true"