問題描述
我正在尋找一種 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"
這篇關于將要通過網絡發送/接收的日期(絕對時間)轉換為 Swift 中的數據?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!