
com.julienlavergne.core.converters.DateTimeConverter Maven / Gradle / Ivy
The newest version!
package com.julienlavergne.core.converters;
import com.github.jmkgreen.morphia.converters.SimpleValueConverter;
import com.github.jmkgreen.morphia.converters.TypeConverter;
import com.github.jmkgreen.morphia.mapping.MappedField;
import com.github.jmkgreen.morphia.mapping.MappingException;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
/**
* Created with IntelliJ IDEA.
* com.julienlavergne.core.User: julien
* Date: 8/23/12
* Time: 22:53
* To change this template use File | Settings | File Templates.
*/
public final class DateTimeConverter extends TypeConverter implements SimpleValueConverter {
public DateTimeConverter() {
super(DateTime.class);
}
@Override
public final Object encode(Object value, MappedField optionalExtraInfo) throws MappingException {
if (value == null) {
return null;
}
if (!(value instanceof DateTime)) {
throw new MappingException("Unable to convert " + value.getClass().getName());
}
//Returns a formatter that combines a full date and time, separated by a 'T' (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).
DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
return dtf.print((DateTime) value);
}
@Override
public DateTime decode(Class targetClass, Object fromDBObject, MappedField optionalExtraInfo) {
try{
if (fromDBObject == null) {
return null;
}
if (fromDBObject instanceof String) {
return DateTime.parse((String) fromDBObject);
}
}
catch(MappingException e){
}
catch(IllegalArgumentException e)
{
}
return null;
//throw new MappingException("Unable to convert " + fromDBObject.getClass().getName());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy