Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timezone problems when reading date from Ormlite

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;
like image 325
Paul Lammertsma Avatar asked Nov 13 '12 09:11

Paul Lammertsma


1 Answers

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.

Easy way: timestamp

The trick is to store it in a UTC timestamp instead:

@DatabaseField(canBeNull = true, dataType = DataType.DATE_LONG)
private Date registration;

Advanced way: persister

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;
    }

}
like image 199
Paul Lammertsma Avatar answered Sep 24 '22 17:09

Paul Lammertsma