当前时间作为 32 位 UNIX 时间戳和时间偏移
Current time as 32bit UNIX timestamp and time offset
我正在使用 android BLE。
需要将当前时间作为 32 位 UNIX 时间戳写入特征。之后以秒为单位写入与 UTC 的当前时区偏移量。可能问题在于转换为 32 字节数组,但我不是 100% 确定。
我做到了,但出了点问题。它上升得非常快,最终超过 0x7FFF,FFFF,即它溢出并变为负值,因为时间戳是一个有符号整数。
private byte[] getCurrentUnixTime() {
int unixTime = (int) (System.currentTimeMillis() / 1000L);
byte[] currentDate = Converter.intTo32ByteArray(unixTime);
return currentDate;
}
private byte[] getCurrentTimeOffset() {
TimeZone tz = TimeZone.getDefault();
Date timeNow = new Date();
int offsetFromUtc = tz.getOffset(timeNow.getTime()) / 1000;
byte[] offsetFromUtcByteArray = Converter.intTo32ByteArray(offsetFromUtc);
return offsetFromUtcByteArray;
}
public static byte[] intTo32ByteArray(int number) {
byte[] byteArray = new byte[]{
(byte) (number >> 24),
(byte) (number >> 16),
(byte) (number >> 8),
(byte) number
};
return byteArray;
}
以下 this 您正在使用正确的转换。
在java
by default, the int data type is a 32-bit signed two's complement
integer, which has a minimum value of -0x7FFFFFFF and a maximum value
of 0x7FFFFFFF-1 oracle.
所以这只是表示的问题(不是数据)。有类似的情况,通过 ARGB 用 int 重复颜色 - 它需要 4 * 8 位,所以值一次为正值,如果你只想显示它,则为负值。
要显示所需的值,您可以将 byte[] 转换为 long,就像这样 example
我解决了这个 int 到字节数组代码转换的问题
byte[] offsetFromUtcByteArray = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) offsetFromUtc).array();
和
byte[] currentDate = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) unixTime).array();
我正在使用 android BLE。
需要将当前时间作为 32 位 UNIX 时间戳写入特征。之后以秒为单位写入与 UTC 的当前时区偏移量。可能问题在于转换为 32 字节数组,但我不是 100% 确定。
我做到了,但出了点问题。它上升得非常快,最终超过 0x7FFF,FFFF,即它溢出并变为负值,因为时间戳是一个有符号整数。
private byte[] getCurrentUnixTime() {
int unixTime = (int) (System.currentTimeMillis() / 1000L);
byte[] currentDate = Converter.intTo32ByteArray(unixTime);
return currentDate;
}
private byte[] getCurrentTimeOffset() {
TimeZone tz = TimeZone.getDefault();
Date timeNow = new Date();
int offsetFromUtc = tz.getOffset(timeNow.getTime()) / 1000;
byte[] offsetFromUtcByteArray = Converter.intTo32ByteArray(offsetFromUtc);
return offsetFromUtcByteArray;
}
public static byte[] intTo32ByteArray(int number) {
byte[] byteArray = new byte[]{
(byte) (number >> 24),
(byte) (number >> 16),
(byte) (number >> 8),
(byte) number
};
return byteArray;
}
以下 this 您正在使用正确的转换。
在java
by default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -0x7FFFFFFF and a maximum value of 0x7FFFFFFF-1 oracle.
所以这只是表示的问题(不是数据)。有类似的情况,通过 ARGB 用 int 重复颜色 - 它需要 4 * 8 位,所以值一次为正值,如果你只想显示它,则为负值。
要显示所需的值,您可以将 byte[] 转换为 long,就像这样 example
我解决了这个 int 到字节数组代码转换的问题
byte[] offsetFromUtcByteArray = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) offsetFromUtc).array();
和
byte[] currentDate = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) unixTime).array();