Getting Date Time in Unix Time as Byte Array which size is 8 bytes with Java Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Getting Date Time in Unix Time as Byte Array which size is 8 bytes with Java without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I know I can get it in 4 bytes like so:

int unixTime = (int)(System.currentTimeMillis() / 1000);
byte[] productionDate = new byte[]{
        (byte) (unixTime >> 24),
        (byte) (unixTime >> 16),
        (byte) (unixTime >> 8),
        (byte) unixTime

};

but is there a way to get it in 8 bytes using shifts?

Answer

Sure, just read as a signed long.

long unixTime = System.currentTimeMillis() / 1000L;

byte[] bytes = new byte[] {
        (byte) (unixTime >> 56),
        (byte) (unixTime >> 48),
        (byte) (unixTime >> 40),
        (byte) (unixTime >> 32),        
        (byte) (unixTime >> 24),
        (byte) (unixTime >> 16),
        (byte) (unixTime >> 8),
        (byte) unixTime
};

Alternatively, using NIO ByteBuffer

ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES)
    .putLong(unixTime);

byte[] bytes = buffer.array();
We are here to answer your question about Getting Date Time in Unix Time as Byte Array which size is 8 bytes with Java - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji