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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29273498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:58:36  来源:igfitidea点击:

Getting Date Time in Unix Time as Byte Array which size is 4 bytes with Java

javadatebytearrayunix-timestamp

提问by Figen Güng?r

How Can I get the date time in unix time as byte array which should fill 4 bytes space in Java?

如何将 unix 时间中的日期时间作为字节数组获取,该数组应该在 Java 中填充 4 个字节的空间?

Something like that:

类似的东西:

byte[] productionDate = new byte[] { (byte) 0xC8, (byte) 0x34,
                    (byte) 0x94, 0x54 };

回答by Jesper

First: Unix timeis a number of secondssince 01-01-1970 00:00:00 UTC. Java's System.currentTimeMillis()returns millisecondssince 01-01-1970 00:00:00 UTC. So you will have to divide by 1000 to get Unix time:

第一:Unix时间是一个数字的因为01-01-1970 00:00:00 UTC。JavaSystem.currentTimeMillis()返回自 01-01-1970 00:00:00 UTC 以来的毫秒数。所以你必须除以 1000 才能得到 Unix 时间:

int unixTime = (int)(System.currentTimeMillis() / 1000);

Then you'll have to get the four bytes in the intout. You can do that with the bit shift operator>>(shift right). I'll assume you want them in big endianorder:

然后你必须在输出中获取四个字节int。您可以使用位移运算符>>(右移)来做到这一点。我假设您希望它们按大端顺序排列:

byte[] productionDate = new byte[]{
        (byte) (unixTime >> 24),
        (byte) (unixTime >> 16),
        (byte) (unixTime >> 8),
        (byte) unixTime

};

回答by Peter Lawrey

You can use ByteBufferto do the byte manipulation.

您可以使用ByteBuffer进行字节操作。

int dateInSec = (int) (System.currentTimeMillis() / 1000);
byte[] bytes = ByteBuffer.allocate(4).putInt(dateInSec).array();

You may wish to set the byte order to little endian as the default is big endian.

您可能希望将字节顺序设置为小端,因为默认是大端。

To decode it you can do

要解码它,你可以做

int dateInSec = ByteBuffer.wrap(bytes).getInt();