I’m using the Drift package with Flutter. DateTime values in Drift tables are stored in UTC. I’ve also chosen to store them as ISO 8601 String values, as described here.
To do the timezone conversion, I’m using a simple Custom TypeConverter that converts DateTime values to/from UTC and local time when reading or writing from the Drift database.
// Part of table definition for a Transaction table
DateTimeColumn get txnDate => dateTime().map(const UtcConverter())();
// Custom TypeConverter to convert UTC/local time
class UtcConverter extends TypeConverter<DateTime, DateTime> {
const UtcConverter();
@override
DateTime fromSql(DateTime fromDb) => fromDb.toLocal();
@override
DateTime toSql(DateTime value) => value.toUtc();
}
I also have a Drift method that compares the txnDate with a local date. Here’s a simplified example.
// Get all transactions that happened in the same month (regardless of year)
return (select(transactions)
..where((t) => t.txnDate.month.equals(currentMonth)))
.get()
The problem seems to be that the UtcConverter only works when writing to the database and retrieving values for use in the app. It doesn’t activate when running queries in Drift.
From what I can tell, t.txnDate
is still in UTC when compared against currentMonth
, which is in local time. As a result, the returned list of matching transactions is inaccurate.
What’s the best way to convert t.txnDate
to local time in the query? I really want to avoid converting currentMonth (and many, many other such instances) into UTC. I can already imagine all the human errors and maintainability issues that path will lead to.
Any help would be much appreciated. Thanks!
1