DateTime(…).toUtc() and DateTime.utc(…) give different results

  • Dart VM version: 2.1.1-dev.1.0 (Wed Jan 9 14:55:46 2019 +0100) on “macos_x64”
  • Using Flutter

The issue is rather straightforward. I would expect DateTime(...).toUtc() to give the same output as DateTime.utc(…) but they don’t.

Given the following example:

DateTime now = DateTime.now();
DateTime toUtc = DateTime(now.year, now.month, now.day).toUtc();
DateTime utc = DateTime.utc(now.year, now.month, now.day);
print("now $now");
print("toUtc $toUtc");
print("utc $utc");

the output will be:

now 2019-04-02 16:28:23.223
toUtc 2019-04-01 22:00:00.000Z
utc 2019-04-02 00:00:00.000Z

whereas I would expect it to be:

now 2019-04-02 16:28:23.223
toUtc 2019-04-02 00:00:00.000Z
utc 2019-04-02 00:00:00.000Z

Author: Fantashit

1 thought on “DateTime(…).toUtc() and DateTime.utc(…) give different results

  1. I think this behavior makes sense.

    The following creates a new DateTime object when the current timestamp are in you own timezone and converts it to a new datetime object where the time is represented as UTC:
    DateTime toUtc = DateTime(now.year, now.month, now.day).toUtc();

    And here you create a DateTime object where you tell Dart that the input are already UTC.
    DateTime utc = DateTime.utc(now.year, now.month, now.day);

    Please see the documentation for the two constructors:
    https://api.dartlang.org/stable/2.2.0/dart-core/DateTime/DateTime.html
    https://api.dartlang.org/stable/2.2.0/dart-core/DateTime/DateTime.utc.html

    And the toUtc() method:
    https://api.dartlang.org/stable/2.2.0/dart-core/DateTime/toUtc.html

Comments are closed.