问题
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