001package org.unix4j.convert; 002 003import java.text.DateFormat; 004import java.text.ParseException; 005import java.text.SimpleDateFormat; 006import java.util.Date; 007 008public class DateConverters { 009 public static final ValueConverter<Date> LONG_TO_DATE = new ValueConverter<Date>() { 010 @Override 011 public Date convert(Object value) throws IllegalArgumentException { 012 if (value instanceof Long) { 013 return new Date(((Long)value).longValue()); 014 } 015 return null; 016 } 017 }; 018 public static class StringToDateConverter implements ValueConverter<Date> { 019 private final DateFormat format; 020 public StringToDateConverter(String pattern) { 021 this(new SimpleDateFormat(pattern)); 022 } 023 public StringToDateConverter(DateFormat format) { 024 this.format = format; 025 } 026 @Override 027 public Date convert(Object value) throws IllegalArgumentException { 028 if (value != null) { 029 try { 030 return format.parse(value.toString()); 031 } catch (ParseException e) { 032 return null; 033 } 034 } 035 return null; 036 } 037 } 038 public static final StringToDateConverter STRING_TO_DATE = new StringToDateConverter(DateFormat.getDateInstance()); 039 040 public static final ValueConverter<Date> DEFAULT = new CompositeValueConverter<Date>().add(LONG_TO_DATE).add(STRING_TO_DATE); 041}