package com.inspect.patrol.linkage.util;

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

public class Cp56Time2aUtil {
    public static Date toDate(byte[] bytes) {
        int milliseconds1 = bytes[0] < 0 ? 256 + bytes[0] : bytes[0];
        int milliseconds2 = bytes[1] < 0 ? 256 + bytes[1] : bytes[1];
        int milliseconds = milliseconds1 + milliseconds2 * 256;
        int minutes = bytes[2] & 63;
        int hours = bytes[3] & 31;
        int days = bytes[4] & 15;
        int months = bytes[5] & 15;
        int years = bytes[6] & 127;
        Calendar aTime = Calendar.getInstance();
        aTime.set(Calendar.MILLISECOND, milliseconds);
        aTime.set(Calendar.MINUTE, minutes);
        aTime.set(Calendar.HOUR_OF_DAY, hours);
        aTime.set(Calendar.DATE, days);
        aTime.set(Calendar.MONTH, months);
        aTime.set(Calendar.YEAR, years + 2000);
        return aTime.getTime();
    }

    public static byte[] toBytes(Date aDate) {
        byte[] result = new byte[7];
        Calendar aTime = Calendar.getInstance();
        aTime.setTime(aDate);
        int milliseconds = aTime.get(Calendar.MILLISECOND);
        result[0] = (byte) (milliseconds % 256);
        result[1] = (byte) (milliseconds / 256);
        result[2] = (byte) aTime.get(Calendar.MINUTE);
        result[3] = (byte) aTime.get(Calendar.HOUR_OF_DAY);
        result[4] = (byte) aTime.get(Calendar.DATE);
        result[5] = (byte) aTime.get(Calendar.MONTH);
        result[6] = (byte) (aTime.get(Calendar.YEAR) % 100);
        return result;
    }
}
