Getting Date Time in Unix Time as Byte Array which size is 4 bytes with Java
15,444
Solution 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
};
Solution 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();
Author by
Figen Güngör
Updated on June 22, 2022Comments
-
Figen Güngör almost 2 years
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 };
-
Joop Eggen about 9 yearsTip, though not more efficient:
... = ByteBuffer.allocate(4).putInt(unixTime).array();
. -
Jesper about 9 yearsIt's shorter, but a lot more overhead than my solution, to allocate a
ByteBuffer
just for this... -
Vishy about 9 years@Jesper true, although with escape analysis in Java 8 the ByteBuffer can be allocated on the stack which is not so expensive.