在Unix时间中以字节数组的形式获取日期时间,Java的大小为8字节

问题描述

我知道我可以像这样用4个字节来获取它:

grid

但是有没有一种方法可以通过移位将其以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();