Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 };
like image 519
Figen Güngör Avatar asked Dec 02 '22 17:12

Figen Güngör


2 Answers

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

};
like image 65
Jesper Avatar answered Dec 05 '22 07:12

Jesper


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();
like image 30
Peter Lawrey Avatar answered Dec 05 '22 06:12

Peter Lawrey