json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Proposal: Always convert DateTime to UTC during serialization

Open Rexios80 opened this issue 2 years ago • 4 comments
trafficstars

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.

Rexios80 avatar Nov 14 '23 17:11 Rexios80

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

Rexios80 avatar Jan 07 '25 00:01 Rexios80

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.

kevmoo avatar Jan 07 '25 00:01 kevmoo

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.

Rexios80 avatar Jan 07 '25 00:01 Rexios80

I'll mark this to consider for the next breaking change. Thanks! PRs welcome!

kevmoo avatar Jan 07 '25 00:01 kevmoo

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?

orkun1675 avatar Oct 10 '25 01:10 orkun1675