ios - 如何将unix时间戳转换为NSData对象?

标签 ios objective-c bluetooth nsdata

我正在使用核心蓝牙写入外围设备。我想将当前的 unix 时间戳发送到传感器,并且我尝试这样做:

// Write timestamp to paired peripheral
NSDate*           measureTime = [NSDate date];
NSDateFormatter*  usDateFormatter = [NSDateFormatter new];
NSLocale*         enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[usDateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.000'Z'"];
[usDateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[usDateFormatter setLocale:enUSPOSIXLocale];  // Should force 24hr time regardless of settings value

NSString *dateString = [usDateFormatter stringFromDate:measureTime];
NSDate* startTime = [usDateFormatter dateFromString:dateString];

uint32_t timestamp = [startTime timeIntervalSince1970];
NSData *timestampData = [NSData dataWithBytes:&timestamp length:sizeof(timestamp)]; // <- Troublemaker
[pairedPeripheral writeValue:timestampData forCharacteristic:currentCharacteristic type:CBCharacteristicWriteWithResponse];

问题是这样的:

我的 32 位时间戳返回了正确的值,但是当我将它转换为 NSData 时,外围设备将它读取为 24 小时时钟值,如下所示:“16:42:96”

我哪里出错了?

编辑

我已经修改了代码以摆脱 NSDateFormatter,正如有人提到的那样,这是不必要的。我似乎仍然得到相同的结果:

// Write timestamp to paired peripheral
NSDate*           measureTime = [NSDate date];
uint64_t timestamp = [measureTime timeIntervalSince1970];
NSData *timestampData = [NSData dataWithBytes:&timestamp length:sizeof(timestamp)]; // <- Troublemaker
[pairedPeripheral writeValue:timestampData forCharacteristic:currentCharacteristic type:CBCharacteristicWriteWithResponse]; 

最佳答案

你很困惑。您发送给外围设备的是自 1970 年以来的整数秒数。这是发送 Unix 时间戳的合理方式,但它不是 24 小时格式的时间,它是一个整数。

您需要更改您的代码以使用 uint64_t 或 uint32_t,因为 Unix 时间戳的数字比 32 位整数大得多。 (我建议使用 uint64_t。)

(请参阅@DonMag 对示例时间戳值的评论,例如 1491580283)

一旦外设接收到该时间,您如何显示它是一个单独的问题,也是您真正应该问的问题。

请注意,如果外围设备的“字节顺序”与您的 iOS 设备不同,则您可能会在发送 int 作为二进制数据时遇到问题。您可能希望将时间戳整数转换为字符串并发送它以避免字节顺序问题。

关于ios - 如何将unix时间戳转换为NSData对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43281780/

相关文章:

ios - 来自 iOS 客户端的 Django 身份验证

ios - fatal error : module map file YogaKit. 未找到模块映射

ios - 关于arm neon编译

c# - MonoTouch 连接到 Azure ACS、Azure SQL/Azure WCF

ios - 发送到释放实例的消息

bluetooth - 如何使用 Bluez 发送低功耗蓝牙 GATT 通知?

ios - 如何从 OBD 设备读取或何时读取 DTC(故障代码)?

C# 相当于 iOS SDK NSDate 和 NSTimeInterval

ios - 应该使用 nil 和 Nil 以及 ios 中的 Null 有什么区别?

ios - 应用程序在后台使用 CoreBluetooth 进行通信