Search code examples
javaandroidtimestampbluetooth-lowenergyunix-timestamp

Current time as 32­bit UNIX timestamp and time offset


I working with android BLE.

Need to write to characteristic Current time as 32­bit UNIX timestamp. After that write Current timezone offset from UTC in seconds. Probably problem is in coverting to 32 byte array but i am not 100% sure.

I did it but something is wrong. It rises very quickly, and eventually passes 0x7FFF,FFFF, i.e. it overflows and becomes negative as timestamp is a signed integer.

    private byte[] getCurrentUnixTime() {
        int unixTime = (int) (System.currentTimeMillis() / 1000L);
        byte[] currentDate = Converter.intTo32ByteArray(unixTime);
        return currentDate;
    }



    private byte[] getCurrentTimeOffset() {
        TimeZone tz = TimeZone.getDefault();
        Date timeNow = new Date();
        int offsetFromUtc = tz.getOffset(timeNow.getTime()) / 1000;
        byte[] offsetFromUtcByteArray = Converter.intTo32ByteArray(offsetFromUtc);
        return offsetFromUtcByteArray;
    }



public static byte[] intTo32ByteArray(int number) {

        byte[] byteArray = new byte[]{
                (byte) (number >> 24),
                (byte) (number >> 16),
                (byte) (number >> 8),
                (byte) number

        };
        return byteArray;
    }

Solution

  • I resolve problem with this int to byte array code conversion

    byte[] offsetFromUtcByteArray = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) offsetFromUtc).array();
    

    and

     byte[] currentDate = ByteBuffer.allocate(4).order(LITTLE_ENDIAN).putInt((int) unixTime).array();