¿Cómo insertar la fecha / hora en la zona UTC en MySQL a través de EclipseLink usando Joda-Time?
Necesito almacenar la fecha / hora en la zona UTC en la base de datos MySQL (de una columna de tipo DATETIME). Cuando un usuario ingresa una fecha, primero se convierte aorg.joda.time.DateTime
por un convertidor JSF.
Antes de insertar esta fecha en la base de datos MySQL, se debe convertir de nuevo ajava.util.Date
- Gracias a EclipseLink.
El siguiente es el convertidor que de nuevo convertidores.org.joda.time.DateTime
ajava.util.Date
aunque no es realmente necesario ver este convertidor.
package joda.converter;
import java.util.Date;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public final class JodaDateTimeConverter implements Converter
{
private static final long serialVersionUID = 1L;
@Override
public Object convertObjectValueToDataValue(Object objectValue, Session session)
{
return objectValue instanceof DateTime?((DateTime) objectValue).withZone(DateTimeZone.UTC).toDate():null;
}
@Override
public Object convertDataValueToObjectValue(Object dataValue, Session session)
{
return dataValue instanceof Date?new DateTime((Date) dataValue):null;
}
@Override
public boolean isMutable()
{
return true;
}
@Override
public void initialize(DatabaseMapping databaseMapping, Session session)
{
databaseMapping.getField().setType(java.util.Date.class);
}
}
En elconvertObjectValueToDataValue()
Método (el primero), el valor del primer parámetro -objectValue
recibida es la fecha / hora UTC correcta convertida por Joda-Time en un convertidor JSF.
Por ejemplo, si ingresé una fecha -02-Oct-2013 11:34:26 AM
entonces, el valor deobjectValue
sería -2013-10-02T06:04:26.000Z
. Esta fecha / hora debe insertarse en la base de datos.
Pero cuando este valor es convertido por esta expresión -(DateTime) objectValue).withZone(DateTimeZone.UTC).toDate()
, nuevamente se evalúa para2013-10-02 11:34:26.0
y este valor se proporciona a la base de datos que es incorrecta.
De todos modos, cómo configurar la zona UTC a(DateTime) objectValue).withZone(DateTimeZone.UTC).toDate()
?
Una propiedad de tipoorg.joda.time.DateTime
Se designa en una clase modelo de la siguiente manera.
@Column(name = "discount_start_date", columnDefinition = "DATETIME")
@Converter(name = "dateTimeConverter", converterClass = JodaDateTimeConverter.class)
@Convert("dateTimeConverter")
private DateTime discountStartDate;
EDITAR: (El siguiente convertidor JSF funciona como se espera junto con el convertidor EclipseLink sobre el cual permanece intacto, desde el únicoresponder hasta ahora por BalusC)
Este es mi convertidor JSF.
package converter;
import java.util.TimeZone;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import util.Utility;
@ManagedBean
@RequestScoped
public final class DateTimeConverter implements Converter
{
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
DateTime dateTime=null;
try
{
dateTime = DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa").withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("IST"))).parseDateTime(value);
}
catch (IllegalArgumentException e)
{
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", Utility.getMessage("datetime.converter.error", DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa").print(DateTime.now().withZone(DateTimeZone.forID("Asia/Kolkata"))))), e);
}
catch(UnsupportedOperationException e)
{
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "", Utility.getMessage("datetime.converter.error", DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa").print(DateTime.now().withZone(DateTimeZone.forID("Asia/Kolkata"))))), e);
}
return dateTime;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
DateTimeFormatter dateTimeFormatter=DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa").withZone(DateTimeZone.forID("Asia/Kolkata")); //This zone will be tackled/handled later from the database to display.
return value instanceof DateTime?dateTimeFormatter.print((DateTime)value):null;
}
}