dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.31k stars 1.59k forks source link

proposal: `DateTime is not UTC` #59129

Open guplem opened 1 year ago

guplem commented 1 year ago

DateTime is not UTC

Description

The DateTime is not in UTC format.

Details

The DateTime object should always be in UTC, specially if it might be serialized/deserialized to be stored on a server or to interact with other dates fetched from the internet.

Having all DateTime objects formatted with UTC will make the code less error-prone.

Kind

Guard against errors

Bad Examples

DateTime currentTime = DateTime.now(); DateTime moonLanding = DateTime(1969, 7, 16, 20, 18, 04);

Good Examples

DateTime currentTime = DateTime.now().toUtc(); DateTime moonLanding = DateTime.utc(1969, 7, 20, 20, 18, 04);

Discussion

I got this need while I was creating a time-sensitive app that had to send DateTime data into Firestore (in string format). I was tracking down a bug that happened due to forgetting to use toUtc() before serializing the date to store it in the database (I was using a custom serializer).

To my knowledge, some formats such as (the only available by default) Iso8601 could be used to serialize/deserialize safely the DateTime, but not all formats will contain timezone data.

This could be an available analyzer rule that could be activated, for example, in the analysis_options.yaml file.

lrhn commented 1 year ago

"The DateTime object should always be in UTC, specially ..."

The "specially" suggests that it's not actually always the case. End-user facing display code may want to use local-time. Recording current clock time in a app should also use local-time.

Also, good example can be DateTime currentTime = DateTime.timestamp();. (DateTime.timestamp) instead of using DateTime.now().toUtc().

guplem commented 1 year ago

The "specially" suggests that it's not actually always the case.

I agree that's why I suggested to male is optional: "This could be an available analyzer rule that could be activated, for example, in the analysis_options.yaml file." I think it might be handy for some people.