Skip to content

DateTime.UtcNow inserted as local time #972

Closed

Description

@KennyEliasson

Hi,

I'm using Dapper and DapperExtensions and found some strange issues that I can narrow down to the following code.

var p = new DynamicParameters();
p.Add("LastSeen", DateTime.UtcNow);
p.Add("userID", user.Id);
connection.Execute("UPDATE Users SET \"lastseen\" = @lastSeen WHERE Id = @userId", p);

Instead of saving the UtcTime it will save the local time.

If I instead set the parameters myself it will work

connection.Execute("UPDATE Users SET \"lastseen\" = @lastSeen WHERE Id = @userId", new { lastSeen = DateTime.UtcNow, userId = 1)};

The following code will work in MySql-environment which brings me to believe this is a Postgres issue instead of a Dapper issue.

Activity

  1. changed the title [-]Inserting UTC datetimes in Dapper DynamicParameters insert the local time instead.[/-] [+]Inserting UTC datetimes in Dapper DynamicParameters inserts the local time instead.[/+] on Feb 5, 2016
  2. KennyEliasson commented on Feb 8, 2016

    @KennyEliasson
    Author

    Been investigating this further and I can see that the DbParameterType is set to TimestampTz.
    Even if I change the DbType to DateTime it inserts the local time.

    Altered my table and added two datetime columns, one with timezone and one without and executed the following code.

    cmd.CommandText = "UPDATE Users SET LastSeen = @lastSeen, Updated = @updated";
    var lastSeen = cmd.CreateParameter(); //Without timestamp
    var updated = cmd.CreateParameter(); //With timestamp
    
    lastSeen.ParameterName = "@lastSeen";
    lastSeen.Direction =  ParameterDirection.Input;
    lastSeen.DbType = DbType.DateTime;
    lastSeen.Value = DateTime.UtcNow;
    
    updated.ParameterName = "@updated";
    updated.Direction = ParameterDirection.Input;
    lastSeen.DbType = DbType.DateTime;
    updated.Value = DateTime.UtcNow;
    
    cmd.Parameters.Add(lastSeen);
    cmd.Parameters.Add(updated);
    
    cmd.ExecuteNonQuery();
    

    LastSeen is of DbParameterType Timestamp and is saved as UTC-time.
    Updated is of DbParameterType TimestampTz and is saved as local time with timezone +01 which also seems wrong.

    For this to work as I expect I need to change all Parameters using TimestampTz to Timestamp instead.

    Is this the expected behavior, to me it seems wrong

  3. changed the title [-]Inserting UTC datetimes in Dapper DynamicParameters inserts the local time instead.[/-] [+]DateTime.UtcNow inserted as local time[/+] on Feb 8, 2016
  4. Emill commented on Feb 9, 2016

    @Emill
    Contributor

    Hi.
    Please note that "timestamp with time zone" is a bad name. It should rather be called "timestamp_utc" or something since internally a timestamptz is just a timestamp (and no attached time zone) that is known to be UTC-time. If you cast a timestamptz to text it will first translate it to local time and then print it with time zone indicator attached (+01 for Sweden). If you cast a timestamptz to/from timestamp without time zone it will also convert it to/from local time.
    When a timestamptz value is transferred over the binary protocol to/from Npgsql, the value is always in UTC. If Npgsql converts it to local time you can always do .ToUniversalTime() to get it in UTC

    So timestamptz is more of a data type that is time-zone aware in the way that you always get the right value when you convert it to some local time zone.

    I also kind of dislike the date/time types in PostgreSQL and the implicit casts of timezones between timestamp and timestamptz...

  5. JCapriotti commented on Apr 26, 2016

    @JCapriotti

    I feel like I'm hitting the same issue but I'm just looking at it differently.

    I'm using "timestamp with time zone" in the PosgreSQL database and inserting .NET DateTime values that have either DateTime.Kind set to either Utc or Local

    The documentation says this about conversions from .NET to PG type:

    .NET value PG type Action
    DateTime(Kind=UTC) timestamptz (default) Send as-is
    DateTime(Kind=Local) timestamptz Convert to UTC locally before sending
    DateTime(Kind=Unspecified) timestamptz Send as-is

    What I'm experiencing is there are no conversions being done. I want to create an isolated test project, but the code is pretty simple...

    Column SQL:

    ALTER TABLE message ADD COLUMN message_timestamp timestamp with time zone;

    Insert these .NET objects

    new DateTime(1977, 12, 28, 6, 0, 0, DateTimeKind.Utc)
    new DateTime(1977, 12, 28, 6, 0, 0, DateTimeKind.Local)
    new DateTime(1977, 12, 28, 6, 0, 0, DateTimeKind.Unspecified)

    The value returned from PgAdmin for all three records is "12/28/1977 06:00:00 CST" (the server is set to Central time zone).

    This behavior seems similar to the issue title, since DateTime.UtcNow will return a DateTime object set to DateTimeKind.Utc. Indeed, I just inserted DateTime.UtcNow, and the record shows "04/26/2016 16:53:23.764448 CDT"

    Am I missing something?

  6. Emill commented on Apr 26, 2016

    @Emill
    Contributor

    How do you set up the parameters in C#?
    Do you assign the NpgsqlDbType?

  7. JCapriotti commented on Apr 26, 2016

    @JCapriotti

    Whoa... no. If I use that, then it works as expected.

    I didn't realize I needed to use that!

  8. Emill commented on Apr 26, 2016

    @Emill
    Contributor

    I know it's a bit complicated.
    Check out at the bottom of http://www.npgsql.org/doc/3.0/types.html. Since Npgsql has no idea what target column type you have in your table, it must choose one data type that is used to transfer the data. For DateTime(Kind=Local,Unspecified), that type is timestamp (without time zone). Once the backend receives it, it converts it to timestamptz.
    I can't understand however why it ends up wrong when you have DateTime with Kind=UTC...

  9. JCapriotti commented on Apr 26, 2016

    @JCapriotti

    Thanks, that type mapping helps.

    I can't understand however why it ends up wrong when you have DateTime with Kind=UTC

    Everything seems to work according to the time zone documentation if I set the command parameter type to NpgsqlDbType.TimestampTZ.

    But yeah, its wrong when I set the parameter to DbType.DateTime and I have DateTime with Kind=UTC. Is it possible npgsql is just leaving off any sort of TZ identifier when it does its insert to PostgreSQL? In other words, npgsql recognizes it as UTC, does no conversion, and gives it to PostgreSQL as is?

    If I insert a time using PgAdmin with no TZ, I think it assumes local time (which for us is Central/US). So that's why I'm wondering if npgsql is just leaving off the TZ...

  10. roji commented on May 8, 2016

    @roji
    Member

    @Emill do you want to investigate the case with Kind=UTC?

  11. Emill commented on May 8, 2016

    @Emill
    Contributor

    I've got no time currently...

  12. roji commented on May 8, 2016

    @roji
    Member

    Sure, no problem - I'll try to look at it.

  13. added this to the 3.0.8 milestone on May 8, 2016
  14. self-assigned this
    on May 8, 2016
  15. 10 remaining items

  16. adicomcz commented on May 22, 2016

    @adicomcz

    I don't think the PostgreSQL is guilty.
    Simple query on same table:

    INSERT INTO tbl_demo
    (id, created)
    VALUES
    (1, '2016/5/22 10:00:00')

    produces:

    id: 1
    created: 2016-05-22 10:00:00

    Result is OK. PostgreSQL assumes it as we expected.

  17. Emill commented on May 22, 2016

    @Emill
    Contributor

    Try this:

    INSERT INTO tbl_demo

    (id, created)
    VALUES
    (1, '2016/5/22 10:00:00+00'::timestamptz)

  18. modified the milestone: 3.0.8 on Jun 7, 2016
  19. roji commented on Jan 8, 2017

    @roji
    Member

    Closing as no additional info was provided, but feel free to post back here and I'll reopen if necessary.

  20. ullahfaheem commented on Feb 1, 2017

    @ullahfaheem

    I am facing a similar issue with Dapper to postgresql:

    setup:
    a DB function:
    foo(v_from character varying, v_to character varying, v_date date)

    Dapper code:

    public static decimal GetValue(DateTime vdate, string cur) {
    
                string sql = @"SELECT _public.foo(@vFrom, @vTo, @vDate)";
                var data = connection.QueryFirstOrDefault<decimal>(
                                                     sql,
                                                     new
                                                     {
                                                         vFrom = cur,
                                                         vTo = cur,
                                                         vDate = valdate,
                                                     }
                                                    );
    }
    
    

    I receive the following error:
    Npgsql.PostgresException : 42883: Funktion _public.foo(text, text, timestamp without time zone) does not exist

    Somehow string is converted to text instead of character varchar. Similar story for DateTime to timestamp.

    Tried the variation with DynamicParameters.Add(), but still the same result.

  21. roji commented on Feb 1, 2017

    @roji
    Member

    This really has nothing to do with this issue..

    Regardless, by default, Npgsql sends NET strings as PostgreSQL text, not varchar. You can specify the NpgsqlDbType on your parameter to make it send varchar instead. Same for DateTime which is mapped to timestamp by default.

    If you still have issues, open a separate issue and we'll take it from there.

  22. Lojka59 commented on Jul 18, 2017

    @Lojka59

    @roji

    @JCapriotti I couldn't reproduce an issue here, below is the code I'm using to test. Can you please submit a code sample of your own that shows the issue?

    i think you should create table with timestamp type (not timestamptz)

    I got same issue as described here:
    i insert DateTime objects from c# (like 11:11:11)
    to postgreSQL table with (TIMESTAMP without time zone) columns
    and result is like 17:11:11 (i got +6 timezone)

    i tryed to manualy change parameter type to timestamp (from timestamptz) and it wokrs fine

    but question is - how can i tell to always treat DateTime objects as timestamp (not timestamptz)

  23. roji commented on Jul 18, 2017

    @roji
    Member

    @Lojka59, you can control Npgsql's sending behavior via NpgsqlParameter's NpgsqlDbType property. If you specify NpgsqlDbType.Timestamp, you timestamp gets passed through as-is, while if you specify NpgsqlDbType.TimestampTZ Npgsql will perform timezone conversions (based on your DateTime.Kind), to attempt to mimic regular PostgreSQL conversions.

    This subject is unfortunately quite complicated... You definitely need to read the Npgsql docs to understand exactly what Npgsql does, but to be honest the situation isn't ideal because of both .NET date/time types (which aren't great) and the fact that things don't map very well between the .NET types and the PostgreSQL ones.

    On the bright side, 3.3 will provide a NodaTime plugin which should make everything much simpler and tighter.

  24. Lojka59 commented on Jul 19, 2017

    @Lojka59

    @roji yeap, i found in this topic, that i can manualy switch NpgsqlDbType of a parameter, thanks.
    i think only 1 moment was unclear = npgsql parameter do not take in count what column type is there in database (with TZ or without) and always send dateTime as TimestampTZ type...

  25. roji commented on Jul 19, 2017

    @roji
    Member

    @Lojka59 ah ok, understood.

    Yes, when Npgsql sends parameters it has no knowledge whatsoever of the types of the columns into which they get written etc. So there really are two different things: the parameter types Npgsql sends - controlled via NpgsqlDbType - and what PostgreSQL does with them, which can include implicit conversions etc.

  26. added theissue type on Jun 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions