package au.net.causal.projo.prefs.jodatime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.ISODateTimeFormat;
import au.net.causal.projo.prefs.PreferencesException;
import au.net.causal.projo.prefs.transform.GenericToStringTransformer;
public class LocalDateToStringTransformer extends GenericToStringTransformer<LocalDate>
{
private final DateTimeFormatter formatter;
public LocalDateToStringTransformer(DateTimeFormatter formatter)
{
super(LocalDate.class);
if (formatter == null)
throw new NullPointerException("formatter == null");
this.formatter = formatter;
}
public LocalDateToStringTransformer()
{
//Be generous with input, allow time fields but they get ignored
this(new DateTimeFormatterBuilder().append(ISODateTimeFormat.date().getPrinter(), ISODateTimeFormat.localDateOptionalTimeParser().getParser()).toFormatter());
}
@Override
protected String valueToString(LocalDate value) throws PreferencesException
{
if (value == null)
return(null);
return(value.toString(formatter));
}
@Override
protected LocalDate stringToValue(String s) throws PreferencesException
{
if (s == null)
return(null);
try
{
return(LocalDate.parse(s, formatter));
}
catch (IllegalArgumentException e)
{
//Thrown when parsing fails
throw new PreferencesException("Could not parse date '" + s + "'.", e);
}
}
}