ios - 将十六进制代码转换为日期 (BLE) - 算法

标签 ios swift

样本日期和相应的十六进制代码

min: 01-Jan-2001 00:00:00 -> Hex code 00 00 00 00
max: 31-Dec-2099 23:59:59 -> Hex code BA 36 8E 7F

Value 0 reckons to 01-Jan-2001 00:00:00 Offset value for UNIX Timestamp: 978307200

如何按照相同的模式将给定的十六进制代码转换为日期?

最佳答案

数据是日期偏移量的大端表示 “引用日期”(2001 年 1 月 1 日 00:00:00 UTC):

let data = Data(bytes: [0xBA, 0x36, 0x8E, 0x7F])
let offset = UInt32(bigEndian: data.withUnsafeBytes { $0.pointee })
let date = Date(timeIntervalSinceReferenceDate: TimeInterval(offset))
print(date) // 2099-12-31 23:59:59 +0000

如果输入真的是十六进制字符串,而不是Data:

let hex = "BA368E7F"
if let offset = UInt32(hex, radix: 16) {
    let date = Date(timeIntervalSinceReferenceDate: TimeInterval(offset))
    print(date) // 2099-12-31 23:59:59 +0000
}

关于ios - 将十六进制代码转换为日期 (BLE) - 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50837814/

相关文章:

ios - 如何 "restart"iOS 应用程序/从 UIApplicationDelegate 实例重新实例化初始 View Controller ?

ios - 水平 UIButton 中的垂直文本

ios - tableView Swift 中的乘积值

ios - 下载 Firebase 存储的 URL 不起作用

ios - Parse PushError 141 invalid function 云代码

Swift - 使用 motionManager 加速度计、陀螺仪和磁力计来移动 SceneKit 节点,就像 iPhone 的移动一样

ios - 检索/设置数组中 UIView 对象的值

ios - UILabel 下边框和右边框

iOS swift - 以编程方式转到下一个自定义 UITabBarController

ios - 如何使用 Swift 4 在 UICollection View 中获得多个选择