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

rwqw0loc  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(347)

我知道我可以用4个字节得到它,就像这样:

int unixTime = (int)(System.currentTimeMillis() / 1000);
byte[] productionDate = new byte[]{
        (byte) (unixTime >> 24),
        (byte) (unixTime >> 16),
        (byte) (unixTime >> 8),
        (byte) unixTime

};

但是有没有一种方法可以让它在8字节内使用移位?

gcxthw6b

gcxthw6b1#

当然,只要读一读签名 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();

相关问题