Skip to content

Instantly share code, notes, and snippets.

@miere
Created July 18, 2013 00:46
Show Gist options
  • Select an option

  • Save miere/6025859 to your computer and use it in GitHub Desktop.

Select an option

Save miere/6025859 to your computer and use it in GitHub Desktop.
Universal, easy to read, date converter.
public class DateConverter extends Converter<Date> {
@Override
public Date convert( String value, Class<Date> clazz ) throws ConversionException {
Date convertedDate = tryToConvertFromLong( value );
if ( convertedDate == null )
convertedDate = tryToConvertFromInternationDateFormat( value );
if ( convertedDate == null )
throwCantConvertValueToDate( value );
return convertedDate;
}
private void throwCantConvertValueToDate( String value ) throws ConversionException {
throw new ConversionException( String.format( "Can't convert '%s' to java.util.Date.", value ) );
}
private Date tryToConvertFromLong( String value ) {
try {
long parsedLong = Long.parseLong( value );
return new Date( parsedLong );
} catch ( Throwable e ) {
return null;
}
}
private Date tryToConvertFromInternationDateFormat( String value ) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
return dateFormat.parse( value );
} catch ( ParseException e ) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment