5

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 };
Figen Güngör
  • 12,169
  • 14
  • 66
  • 108

2 Answers2

17

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

};
Jesper
  • 202,709
  • 46
  • 318
  • 350
3

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();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • It's shorter, but a lot more overhead than my solution, to allocate a `ByteBuffer` just for this... – Jesper Mar 26 '15 at 08:20
  • @Jesper true, although with escape analysis in Java 8 the ByteBuffer can be allocated on the stack which is not so expensive. – Peter Lawrey Mar 26 '15 at 08:26