Java 当前时间为32;位UNIX时间戳和时间偏移
我和安卓一起工作 需要以32位UNIX时间戳的形式写入特征当前时间。在此之后,以秒为单位写入当前时区与UTC的偏移量。可能问题在于转换为32字节数组,但我不是100%确定 我做了,但有点不对劲。它上升得非常快,最终通过0x7FFF,FFFF,也就是说,由于时间戳是有符号整数,它会溢出并变为负数Java 当前时间为32;位UNIX时间戳和时间偏移,java,android,timestamp,bluetooth-lowenergy,unix-timestamp,Java,Android,Timestamp,Bluetooth Lowenergy,Unix Timestamp,我和安卓一起工作 需要以32位UNIX时间戳的形式写入特征当前时间。在此之后,以秒为单位写入当前时区与UTC的偏移量。可能问题在于转换为32字节数组,但我不是100%确定 我做了,但有点不对劲。它上升得非常快,最终通过0x7FFF,FFFF,也就是说,由于时间戳是有符号整数,它会溢出并变为负数 private byte[] getCurrentUnixTime() { int unixTime = (int) (System.currentTimeMillis() / 1
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;
}
下面是使用rigth转换的示例
在爪哇
默认情况下,int数据类型是32位有符号2的补码
整数,最小值为-0x7FFFFFFF,最大值为
0x7FFFFFFF-1的
所以这只是一个演示(而不是数据)的问题。类似的情况是,通过ARGB用int重新表示颜色-它需要4*8位,所以值只有一次为正数,如果您想显示它,则为负数
要显示所需的值,可以将字节[]转换为long,如图所示我解决了int-To-byte数组代码转换的问题
byte[] offsetFromUtcByteArray = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) offsetFromUtc).array();
及
byte[] currentDate = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) unixTime).array();