Skip to content

UTC DateTime is not saved correctly when Postgres server is set to time zone other than UTC #2209

Closed

Description

@nheilbuth

Steps to reproduce

When postgresql.conf has this setting:
timezone = 'Europe/Brussels'
(Europe/Brussels is UTC + 1)

This code will save the timestamp 1 hour too early (and exception will be thrown)

var timestamp = DateTime.UtcNow;

using (var command = new NpgsqlCommand())
{
  var sql = "INSERT INTO testtable (id, timestamp) VALUES (@id, @timestamp)";

  command.Connection = connection;
  command.CommandText = sql;
  command.Parameters.Add(new NpgsqlParameter("timestamp", timestamp));
  command.Parameters.Add(new NpgsqlParameter("id", 1));

  command.ExecuteNonQuery();
}

using (var command = new NpgsqlCommand())
  {
  var sql = "SELECT * FROM testtable WHERE id = @id";

  command.Connection = connection;
  command.CommandText = sql;
  command.Parameters.Add(new NpgsqlParameter("id", 1));

  var reader = command.ExecuteReader();
  if (reader.Read())
  {
    var resultTimestamp = Convert.ToDateTime(reader["timestamp"]);

    if (!Compare(resultTimestamp.ToUniversalTime(), timestamp.ToUniversalTime()))
      throw new Exception("Result was not as expected");
    }
  }

...

 static bool Compare(DateTime dt1, DateTime dt2)
 {
      return dt1.Year == dt2.Year &&
                 dt1.Month == dt2.Month &&
                 dt1.Day == dt2.Day &&
                 dt1.Hour == dt2.Hour &&
                 dt1.Minute == dt2.Minute &&
                 dt1.Second == dt2.Second;
 }

When setting postgresql.conf timezoen to:
timezone = 'UTC'
...the above code works as expected and does not throw an exception

The issue

When saving a DateTime that has Kind = UTC, I expect it to be saved as UTC with the exact hour value being passed.
This is not what happens. If saving the value "yyyy-mm-dd 11:00:00" as UTC the value in postgres will be 11:00:00 as local time and converted to UTC it will be 10:00:00. The expected values is 12:00:00 local and 11:00:00 UTC

Postgres server timezone setting = UTC will produce the correct result. Other timezone settings will not (only tested with 'Europe/Brussels' value).
This issue only exists in NpgSql 4.x
NpgSql 3.x works as expected regardless of server timezone setting

Further technical details

Npgsql version: 4.0/4.3
PostgreSQL version: 9.6
Operating system: Windows 10

Activity

  1. austindrenski commented on Oct 31, 2018

    @austindrenski
    Contributor

    I'm not exactly sure what's happening, but I can take a look this evening if no one else has had time to respond before then.

    In the meantime, here's a possible explanation and something to try on your end.

    Possible explanation

    The wire protocol sends timestamp values as signed 64-bit integers and Npgsql reads them into NpgsqlDateTime like so:

    var value = buf.ReadInt64();
    if (value == long.MaxValue)
    return NpgsqlDateTime.Infinity;
    if (value == long.MinValue)
    return NpgsqlDateTime.NegativeInfinity;
    if (value >= 0) {
    var date = (int)(value / 86400000000L);
    var time = value % 86400000000L;
    date += 730119; // 730119 = days since era (0001-01-01) for 2000-01-01
    time *= 10; // To 100ns
    return new NpgsqlDateTime(new NpgsqlDate(date), new TimeSpan(time));

    That calls a constructor which defaults the DateTimeKind to DateTimeKind.Unspecified:

    public NpgsqlDateTime(NpgsqlDate date, TimeSpan time, DateTimeKind kind = DateTimeKind.Unspecified)
    : this(KindToInternalType(kind), date, time) {}

    When you convert with .ToDateTime, the ticks and kind are simply passed forward:

    public DateTime ToDateTime()
    {
    if (!IsFinite)
    throw new InvalidCastException("Can't convert infinite timestamp values to DateTime");
    if (_date.DaysSinceEra < 0 || _date.DaysSinceEra > MaxDateTimeDay)
    throw new InvalidCastException("Out of the range of DateTime (year must be between 1 and 9999)");
    return new DateTime(Ticks, Kind);
    }

    So now you're working with instances of the normal CLR DateTime, but I suspect the DateTimeKind of your resultTimestamp is still set to DateTimeKind.Unspecified. That's important because you then call .ToUniversalTime which has this remark in the docs (emphasis added):

    Starting with the .NET Framework version 2.0, the value returned by the ToUniversalTime method is determined by the Kind property of the current DateTime object. The following table describes the possible results.

    Kind Results
    Utc No conversion is performed.
    Local The current DateTime object is converted to UTC.
    Unspecified The current DateTime object is assumed to be a local time, and the conversion is performed as if Kind were Local.

    So my suspicion is that you're getting a value back in the database timezone, but your code is treating it as though its in the local timezone when converting it into UTC.

    Next steps

    Have you tried adjusting the timezone in your connection string or by setting the PGTZ environment variable?

    Related

    #1803
    #1803 (comment)

  2. nheilbuth commented on Oct 31, 2018

    @nheilbuth
    Author

    Hi Austin

    Thanks for the quick reply.
    I dont think thats what's happening.

    If I inspect the reader["timestamp"] value directly (before Convert.ToDateTime), it has Kind.Local. The value is equal to the expected UTC value.

    Also the error happens on INSERT (I should have been more clear about that). The value in Postgres is wrong.

    I have just run the test code. Time is now 17:16 local time (UTC+1). So I would expect to have 17:16 local and 16:16 UTC in the database.
    I get this output in DBeaver:
    npgsql4

    Downgrading to NpgSql 3.2.7 and running again (5 minutes later), gives the expected result:
    npgsql3

    Btw I wasnt looking for a quick workaround. For now I'm settings postgres server to UTC as a workaround.
    I was merely reporting the bug for the sake of the NpgSql project

  3. austindrenski commented on Oct 31, 2018

    @austindrenski
    Contributor

    Working with timezone-aware databases is a headache. Whenever possible, we recommend that users go turtles UTC all the way down. That is, only convert from/to local time when displaying to a human user.

    Thanks for the quick reply.
    I dont think thats what's happening.

    If I inspect the reader["timestamp"] value directly (before Convert.ToDateTime), it has Kind.Local. The value is equal to the expected UTC value.

    When saving a DateTime that has Kind = UTC, I expect it to be saved as UTC with the exact hour value being passed. This is not what happens.

    This does appear to be happening. If I've understood you correctly, running SELECT * FROM testtable returns the UTC value inserted by Npgsql.

    Is that not the case?

    If saving the value "yyyy-mm-dd 11:00:00" as UTC the value in postgres will be 11:00:00 as local time and converted to UTC it will be 10:00:00. The expected values is 12:00:00 local and 11:00:00 UTC

    PostgreSQL is showing you 11:00:00, but it isn't in local time, it's a UTC value. See below for some idea of why applying AT TIME ZONE 'UTC' to the already-is-UTC value returns 10:00:00.

    Also the error happens on INSERT (I should have been more clear about that). The value in Postgres is wrong.

    As above, I'm not sure that this is an error.

    Your code inserts a timestamp and PostgreSQL stores it without any timezone information, as expected. The local column (which is a UTC value) in your first screenshot appears to show exactly that.

    Converting the timestamp into a timestamptz is where things get wonky. See below for citations discussing why this happens:

    Per #1803 (comment) and #1940:

    Timestamp without time zone

    • By default DateTime is always sent as timestamp. No conversion is done. This is a breaking change.
    • timestamp is read as a DateTime with Kind=Unspecified. Same behavior as today.
    • It will no longer be possible to write DateTimeOffset to timestamp as it is in 3.x (trying to read currently throws an exception), I'm not sure why this was allowed in the first place. This is a breaking change.

    Per the PosgreSQL docs:

    Conversions between timestamp without time zone and timestamp with time zone normally assume that the timestamp without time zone value should be taken or given as timezone local time. A different time zone can be specified for the conversion using AT TIME ZONE.

  4. nheilbuth commented on Nov 1, 2018

    @nheilbuth
    Author

    Ok, first off the timestamp in my screenshot is local time not UTC.
    Just to be clear I made the same test and screenshots in pgAdmin (to include the +/- timezone in display values).
    Now passing this value:
    new DateTime(2018, 11, 1, 10, 0, 0, DateTimeKind.Utc);
    pgAdmin shows:
    image
    (+01 confirming that the value is in local time)

    What I get from the comments on #1803 is that it sounds like this is a deliberate breaking change from 3.x to 4!?
    That, by default, DateTime.Kind is now ignored and DateTime is passed to Postgres as a timestamp (without time zone)!?

    I can confirm that using this code, UTC is now actually saved as UTC:

    var parameter = new NpgsqlParameter("timestamp", NpgsqlDbType.TimestampTz) { Value = timestamp };
    command.Parameters.Add(parameter);
    

    Not sure I understand the reason for this change, but I suspect other to run into the same issue.
    Would it be possible to configure NpgSql to globally use TimestampTz for DateTime?

  5. roji commented on Nov 1, 2018

    @roji
    Member

    @nheilbuth there's one critical missing piece of information that's missing from your original post: the column types into which you're inserting.

    As the release notes for 4.0 say, we had a behavior change where DateTime is always sent to PostgreSQL as timestamp without time zone (in 3.0 this depended on the Kind) - more detail is available in #1803 which you've already looked at. Now, if the database column you're inserting into is a timestamp with time zone, PostgreSQL will perform a conversion as per the docs. This could cause the somewhat unexpected behavior you're experiencing.

    As @austindrenski mentioned above, at least in my view it's best to use columns of type timestamp without time zone (there are other opinions on this). This makes your database completely timezone un-aware - no timezone conversions will occur anywhere, neither in the driver nor in the database. IMHO this is a good thing and the way interaction with databases should work.

    Let us know if this clarifies things.

  6. nheilbuth commented on Nov 1, 2018

    @nheilbuth
    Author

    Ah sorry. The column type is timestamptz.

    Yes that clarifies things.

    You might be right that using timestamp without time zone is best practice, but it still seems a bit odd to essentially drop support for timestamptz.
    Migrating existing projects that use timestamptz could be quite a headache, and if you use Dapper on top of NpgSql, passing NpgsqlDbType.TimestampTz to the parameter is not an option.

  7. roji commented on Nov 2, 2018

    @roji
    Member

    You might be right that using timestamp without time zone is best practice, but it still seems a bit odd to essentially drop support for timestamptz.

    Support for timestamptz definitely isn't dropped - you simply have to explicitly specify that you want to send timestamptz by setting NpgsqlDbType.Timestamptz on your NpgsqlParameter instance. This is again mentioned in the release notes, although I can see that the date/time mapping docs are out of date - I'll fix that soon.

    In addition, DateTimeOffset is also sent as timestamptz by default, as before (although once again I can't say I recommend it).

    Migrating existing projects that use timestamptz could be quite a headache, and if you use Dapper on top of NpgSql, passing NpgsqlDbType.TimestampTz to the parameter is not an option.

    That is not true - you can use Dapper's ICustomQueryParameter to set NpgsqlDbType (see this stackoverflow for an example).

    Am going to close as no further action is needed on our side, but feel free to continue posting questions or suggestions to this issue.

  8. nheilbuth commented on Nov 2, 2018

    @nheilbuth
    Author

    That is not true - you can use Dapper's ICustomQueryParameter to set NpgsqlDbType (see this stackoverflow for an example).

    Thanks that might come in handy

  9. foote-Greg commented on Jun 30, 2019

    @foote-Greg

    So if it is best practice to store the values as UTC in timestamp without timezone, What about the use case for SAAS where the application will connect to a separate database per tenant , but the codebase is the same. Where is the best place to do the conversion ? The tenant will have only 1 timezone for all users of the app... Is there a configuration call or an EF Core event hook I can place code in to lookup the current user's timezone and apply the necessary translation ?

    Thanks,
    Greg

  10. austindrenski commented on Jun 30, 2019

    @austindrenski
    Contributor

    Where is the best place to do the conversion ?

    Is there a configuration call or an EF Core event hook I can place code in to lookup the current user's timezone and apply the necessary translation ?

    Hopefully I haven't misunderstood, but if you're asking, "where in the EF Core infrastructure should I handle time zone conversions?", then I believe our recommendation is still to avoid doing that work in the driver/ORM layer altogether.

    Just one opinion, of course, but I expect it to almost always be far simpler to push those conversions to the app boundary, where (for example) NodaTime can work it's magic on incoming/outgoing data at the first/last possible moment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions