json_serializable.dart
json_serializable.dart copied to clipboard
Proposal: Always convert DateTime to UTC during serialization
Since dates should pretty much always be stored in UTC would it be reasonable to automatically convert DateTime objects to UTC during serialization? Could this at least be an option in the generator? I know I could write my own DateTime converter but then I have to remember to use it every time I create a new DateTime field.
I see https://github.com/google/json_serializable.dart/pull/811, but that was abandoned. I think making this a generator setting, maybe off by default to prevent issues with existing codebases, would be ideal.
I made a custom_lint rule to enforce creating DateTime objects using the DateTime.timestamp() instead of DateTime.now() constructor, but I feel like this should still be an option
I get your pitch here, certainly. The only issue is backwards compat at this point. Not sure how to move forward gracefully here. Suggestions welcome.
Would it be acceptable to implement a breaking change to address this issue? Currently, all projects are in one of the following states:
- Developers are aware that their timestamps are stored as localized strings (I was unaware of this initially)
- Developers are inadvertently storing their timestamps as localized strings, resulting in an invalid database (this happened to me)
- Developers are manually verifying that their timestamps are stored in UTC (I am currently doing this)
Considering that DateTime.timestamp() was introduced relatively recently, I believe this is a common pitfall to encounter when working with JSON serialization.
I'll mark this to consider for the next breaking change. Thanks! PRs welcome!
It would be great to introduce this using a flag that we can toggle on.
Is there a way to override the default DateTime behaviour project wide without needing to add @JsonSerializable(converters: [...]) in every site?