Created
July 18, 2013 00:46
-
-
Save miere/6025859 to your computer and use it in GitHub Desktop.
Universal, easy to read, date converter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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