Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java将Unix时间中的日期时间作为大小为8字节的字节数组获取_Java_Date_Byte - Fatal编程技术网

使用Java将Unix时间中的日期时间作为大小为8字节的字节数组获取

使用Java将Unix时间中的日期时间作为大小为8字节的字节数组获取,java,date,byte,Java,Date,Byte,我知道我可以用4个字节得到它,就像这样: int unixTime = (int)(System.currentTimeMillis() / 1000); byte[] productionDate = new byte[]{ (byte) (unixTime >> 24), (byte) (unixTime >> 16), (byte) (unixTime >> 8), (byte) unixT

我知道我可以用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;
字节[]字节=新字节[]{
(字节)(unixTime>>56),
(字节)(unixTime>>48),
(字节)(unixTime>>40),
(字节)(unixTime>>32),
(字节)(unixTime>>24),
(字节)(unixTime>>16),
(字节)(unixTime>>8),
(字节)unixTime
};
或者,使用NIO ByteBuffer

ByteBuffer buffer=ByteBuffer.allocate(Long.BYTES)
.putLong(unixTime);
byte[]bytes=buffer.array();

此代码需要工作多长时间?在接下来的18年中,“unix时间”可以容纳31位,即4个有符号字节。因此,如果您想将其分成8个字节,只需在左侧添加4个字节的零,即最重要的一端。@user13784117您是否太年轻,无法从中学习任何内容?一点也不。但我知道明年会出现的代码和不会出现的代码之间的区别。我怀疑OP的代码是后者:毕竟,这是一个相当基本的问题。如果代码是为了学习,学习是为了生活,那么如果应用你的建议,他们将学习完全错误的东西。@user13784117woops idk我怎么忘了这么做。