package au.net.causal.projo.prefs.jodatime;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import au.net.causal.projo.prefs.PreferencesException;
import au.net.causal.projo.prefs.transform.GenericToStringTransformer;
public class DateTimeToStringTransformer extends GenericToStringTransformer<DateTime>
{
private final DateTimeFormatter formatter;
public DateTimeToStringTransformer(DateTimeFormatter formatter)
{
super(DateTime.class);
if (formatter == null)
throw new NullPointerException("formatter == null");
this.formatter = formatter;
}
public DateTimeToStringTransformer()
{
this(ISODateTimeFormat.dateTime().withOffsetParsed());
}
@Override
protected String valueToString(DateTime value) throws PreferencesException
{
if (value == null)
return(null);
return(value.toString(formatter));
}
@Override
protected DateTime stringToValue(String s) throws PreferencesException
{
if (s == null)
return(null);
try
{
return(DateTime.parse(s, formatter));
}
catch (IllegalArgumentException e)
{
//Thrown when parsing fails
throw new PreferencesException("Could not parse date '" + s + "'.", e);
}
}
}