以 Unix 时间获取日期时间作为大小为 8 字节的字节数组 Java
Getting Date Time in Unix Time as Byte Array which size is 8 bytes with Java
我知道我可以像这样用 4 个字节得到它:
int unixTime = (int)(System.currentTimeMillis() / 1000);
byte[] productionDate = new byte[]{
(byte) (unixTime >> 24),
(byte) (unixTime >> 16),
(byte) (unixTime >> 8),
(byte) unixTime
};
但是有没有办法使用移位将其转换为 8 个字节?
当然可以,只需阅读带符号的 long
。
long unixTime = System.currentTimeMillis() / 1000L;
byte[] bytes = new byte[] {
(byte) (unixTime >> 56),
(byte) (unixTime >> 48),
(byte) (unixTime >> 40),
(byte) (unixTime >> 32),
(byte) (unixTime >> 24),
(byte) (unixTime >> 16),
(byte) (unixTime >> 8),
(byte) unixTime
};
或者,使用 NIO ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES)
.putLong(unixTime);
byte[] bytes = buffer.array();
我知道我可以像这样用 4 个字节得到它:
int unixTime = (int)(System.currentTimeMillis() / 1000);
byte[] productionDate = new byte[]{
(byte) (unixTime >> 24),
(byte) (unixTime >> 16),
(byte) (unixTime >> 8),
(byte) unixTime
};
但是有没有办法使用移位将其转换为 8 个字节?
当然可以,只需阅读带符号的 long
。
long unixTime = System.currentTimeMillis() / 1000L;
byte[] bytes = new byte[] {
(byte) (unixTime >> 56),
(byte) (unixTime >> 48),
(byte) (unixTime >> 40),
(byte) (unixTime >> 32),
(byte) (unixTime >> 24),
(byte) (unixTime >> 16),
(byte) (unixTime >> 8),
(byte) unixTime
};
或者,使用 NIO ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES)
.putLong(unixTime);
byte[] bytes = buffer.array();