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

青春壹個敷衍的年華 提交于 2021-02-07 19:50:59

问题


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

Something like that:

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

回答1:


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

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

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

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

};



回答2:


You can use ByteBuffer to do the byte manipulation.

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();


来源:https://stackoverflow.com/questions/29273498/getting-date-time-in-unix-time-as-byte-array-which-size-is-4-bytes-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!