Skip to content

Instantly share code, notes, and snippets.

@hugithordarson
Last active July 3, 2018 16:09
Show Gist options
  • Save hugithordarson/cb38a4ee0c4cfd5061b74078e137054d to your computer and use it in GitHub Desktop.
Save hugithordarson/cb38a4ee0c4cfd5061b74078e137054d to your computer and use it in GitHub Desktop.
package x;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Objects;
public class DateTimeFormatterWrapper extends Format {
private DateTimeFormatter _wrappedFormatter;
public DateTimeFormatterWrapper( DateTimeFormatter wrappedFormatter ) {
Objects.requireNonNull( wrappedFormatter );
_wrappedFormatter = wrappedFormatter;
}
@Override
public StringBuffer format( Object object, StringBuffer toAppendTo, FieldPosition pos ) {
toAppendTo.append( _wrappedFormatter.format( (TemporalAccessor)object ) );
return toAppendTo;
}
@Override
public Object parseObject( String source, ParsePosition pos ) {
pos.setIndex( source.length() );
return _wrappedFormatter.parse( source );
}
public static void main( String[] args ) {
DateTimeFormatterWrapper f = new DateTimeFormatterWrapper( DateTimeFormatter.ofPattern( "dd.MM.YYYY" ) );
System.out.println( f.format( LocalDate.of( 1979, 11, 9 ) ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment