ios - How to convert unix timestamp to NSData object? -
i'm using core bluetooth write peripheral. send current unix timestamp sensor, , have attempted so:
// write timestamp 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:×tamp length:sizeof(timestamp)]; // <- troublemaker [pairedperipheral writevalue:timestampdata forcharacteristic:currentcharacteristic type:cbcharacteristicwritewithresponse];
here's issue:
my 32 bit timestamp returns correct value, when convert nsdata, peripheral reads 24 hour clock value this: "16:42:96"
where making error?
edit
i have modified code rid of nsdateformatter, has mentioned unnecessary. still seem getting same result:
// write timestamp paired peripheral nsdate* measuretime = [nsdate date]; uint64_t timestamp = [measuretime timeintervalsince1970]; nsdata *timestampdata = [nsdata datawithbytes:×tamp length:sizeof(timestamp)]; // <- troublemaker [pairedperipheral writevalue:timestampdata forcharacteristic:currentcharacteristic type:cbcharacteristicwritewithresponse];
you confused. you're sending peripheral integer number of seconds since 1970. that's reasonable way send unix timestamp, not time in 24 hour format, integer.
you need change code use uint64_t or uint32_t since unix timestamps larger numbers fit in 32 bit integer. (i suggest using uint64_t.)
(see @donmag's comment sample timestamp values, 1491580283)
how display time once received peripheral separate question, , question should asking.
note may run problems sending int binary data if peripheral has different "endian-ness" ios device. might want convert timestamp integer string , send in order avoid endian-ness problem.
Comments
Post a Comment