将要通过网络发送/接收的日期(绝对时间)转换为 Swift 中的数据?
- 作者: 幸福可恶的小朋友
- 来源: 51数据库
- 2022-10-25
问题描述
我正在寻找一种 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"
推荐阅读
热点文章
检查拆分键盘
0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView
0
Activity 启动时显示软键盘
0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧
0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画
0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?
0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?
0
禁用 iPhone 中键盘的方向
0
Android 2.3 模拟器上的印地语键盘问题
0
keyDown 没有被调用
0
