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 formatYYYY-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:
Advanced way: persister
If you want to get your hands dirty writing your own persister, this is how it's done:
Where:
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:
Then there is no need to configure each Date field with
dataType = DataType.DATE_LONG
.