Util.java Source code

Java tutorial

Introduction

Here is the source code for Util.java

Source

import java.util.Calendar;
import java.util.Date;

public class Util {

    /**
     * Unpacks date stored in kdb format.
     * 
     * @param d
     * @return
     */
    public static Date unpackDate(byte[] d) {
        // Byte bits: 00000000 11111111 22222222 33333333 44444444
        // Contents : 00YYYYYY YYYYYYMM MMDDDDDH HHHHMMMM MMSSSSSS
        int year = (d[0] << 6) | ((d[1] >> 2) & 0x0000003F);
        int month = ((d[1] & 0x00000003) << 2) | ((d[2] >> 6) & 0x00000003);
        int day = (d[2] >> 1) & 0x0000001F;
        int hour = ((d[2] & 0x00000001) << 4) | ((d[3] >> 4) & 0x0000000F);
        int minute = ((d[3] & 0x0000000F) << 2) | ((d[4] >> 6) & 0x00000003);
        int second = d[4] & 0x0000003F;
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day, hour, minute, second);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    public static byte[] packDate(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // Byte bits: 00000000 11111111 22222222 33333333 44444444
        // Contents : 00YYYYYY YYYYYYMM MMDDDDDH HHHHMMMM MMSSSSSS
        byte[] bytes = new byte[5];
        int s = c.get(Calendar.SECOND);
        int m = c.get(Calendar.MINUTE);
        int h = c.get(Calendar.HOUR_OF_DAY);
        int d = c.get(Calendar.DATE);
        int mm = c.get(Calendar.MONTH) + 1;
        int y = c.get(Calendar.YEAR);

        bytes[4] = (byte) ((m << 6) | s);
        bytes[3] = (byte) ((m >> 2) | (h << 4));
        bytes[2] = (byte) ((h >> 4) | (d << 1) | (mm << 6));
        bytes[1] = (byte) ((mm >> 2) | (y << 2));
        bytes[0] = (byte) (y >> 6);

        return bytes;
    }
}