Timezone problems when reading date from Ormlite

2019-03-18 18:47发布

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;

2条回答
Anthone
2楼-- · 2019-03-18 19:30

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

}
查看更多
干净又极端
3楼-- · 2019-03-18 19:36

If you're looking for a global way to configure how OrmLite persists Date fields, you can use the DataPersisterManager class (Github).

For example, to save all Dates as Longs in UTC (milliseconds since epoch) instead of the default, which is Strings without timezones, you can do this:

    DataPersisterManager.registerDataPersisters(DateLongType.getSingleton());

Then there is no need to configure each Date field with dataType = DataType.DATE_LONG.

查看更多
登录 后发表回答