I discovered that the dates being read through Ormlite don't return correctly when changing my device's time zone.
For instance, when switching from Amsterdam time to London time, the date should shift forward an hour. However, when reading the date from the database, it returns the same time, but now in the London time zone.
I'm storing my field as follows:
@DatabaseField(canBeNull = true)
private Date registration;
Looking into the database, I discovered that Ormlite by default stores Date
objects in the format YYYY-MM-DD HH:MM:SS.SSS
. As there is no information about the time zone, it assumes the device's current time zone.
The trick is to store it in a UTC timestamp instead:
@DatabaseField(canBeNull = true, dataType = DataType.DATE_LONG)
private Date registration;
If you want to get your hands dirty writing your own persister, this is how it's done:
@DatabaseField(persisterClass = DateConverter.class)
private Date registration;
Where:
public static class DateConverter extends LongType {
private static final DateConverter singleton = new DateConverter();
protected DateConverter() {
super(SqlType.LONG, new Class<?>[] {
Date.class
});
}
public static DateConverter getSingleton() {
return singleton;
}
@Override
public Object javaToSqlArg(FieldType fieldType, Object javaObject)
throws SQLException {
if (javaObject instanceof Date) {
return ((Date) javaObject).getTime();
}
return javaObject;
}
@Override
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos)
throws SQLException {
if (sqlArg instanceof Long) {
return new Date((Long) sqlArg);
}
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With