DateTimeStringCodec implements BlockCodec<Date> { @Override public byte[] encode(Date data, int bitLength) throws BlockCodecException { try { if (this.nullable && data == null) { byte[] result = new byte[this.format.length()]; Arrays.fill(result, this.nullByte); return result; } return new SimpleDateFormat(this.format).format(data).getBytes(); } catch (Exception ex) { throw new BlockCodecException("date encode failure. " + ex.getMessage(), ex); } } DateTimeStringCodec(); String getNullable(); void setNullable(String nullable); String getNullByte(); void setNullByte(String nullByte); String getFormat(); void setFormat(String format); @Override Date zeroValue(); @Override Date decode(byte[] data, int bitLength); @Override byte[] encode(Date data, int bitLength); @Override void reset(); @Override String getValueType();  }
@Test public void testEncode() throws Exception { DateTimeStringCodec codec = new DateTimeStringCodec(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 1992); cal.set(Calendar.MONTH, 1); cal.set(Calendar.DATE, 18); cal.set(Calendar.HOUR_OF_DAY, 13); cal.set(Calendar.MINUTE, 20); cal.set(Calendar.SECOND, 15); cal.set(Calendar.MILLISECOND, 27); long time = cal.getTimeInMillis(); codec.setFormat("yyyyMMdd"); Assert.assertArrayEquals("19920218".getBytes(), codec.encode(new Date(time), 8)); codec.setFormat("yyyyMMddHHmm"); Assert.assertArrayEquals("199202181320".getBytes(), codec.encode(new Date(time), 12)); codec.setNullByte("00"); codec.setNullable("y"); Assert.assertArrayEquals( new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, codec.encode(null, 12)); }