Timezone problems when reading date from Ormlite

纵然是瞬间 提交于 2019-12-03 17:09:29

问题


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;

回答1:


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

}



回答2:


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.



来源:https://stackoverflow.com/questions/13358207/timezone-problems-when-reading-date-from-ormlite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!