Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Kind set to unspecified, not UTC, upon loading from database

When I create a Buyin object the response from the ASP.NET MVC controller, (return Json(response, JsonRequestBehavior.AllowGet);, looks like this:

"Buyin": {
        "Id": 95,
        "PlayerSessionId": 88,
        "PlayerId": 45,
        "PlayerName": "Alan",
        "Amount": 888,
        "BuyinType": "Credits",
        "Description": null,
        "Authorized": true,
        "SignPath": "~/Signs/Buyins\\95.png",
        "Payment": null,
        "CreationDate": "/Date(1477242738042)/"
    },

If I convert that on Epoch Converter I get this time: GMT: Sun, 23 Oct 2016 17:12:18.042 GMT

Looking in the database the stored datetime seems to be correct:

95  NULL    1   1   2016-10-23 17:12:18.043

When the response is sent out the Kind is set to UTC.

Now I call a controller to get all my data and all of the dates have several hours added to it:

 {
    "Id": 95,
    "PlayerSessionId": 88,
    "PlayerId": 45,
    "PlayerName": "Alan",
    "Amount": 888,
    "BuyinType": "Credits",
    "Description": null,
    "Authorized": true,
    "SignPath": "~/Signs/Buyins\\95.png",
    "Payment": null,
    "CreationDate": "/Date(1477267938043)/"
}

1477267938043 = GMT: Mon, 24 Oct 2016 00:12:18.043 GMT

However when I request this object I can see that the actual object has the correct date set: enter image description here

But the Kind is set to Unspecified so I think this is causing the problem.

For the moment I don't have not set any globalization settings.

So basically my question is: When ASP.NET MVC loads the dates from the database is there a way to tell the server to load the dates with Kind set to UTC as I think that is the problem?

The database is saved and loaded using Entity Framework.

Update after the accepted answer

The accepted answer was great however my date values was already stored in the Database as UTC dates so I modified GetDateTime to this:

public override DateTime GetDateTime(int ordinal)
{
    var date = base.GetDateTime(ordinal);
    var utcDate = DateTime.SpecifyKind(date, DateTimeKind.Utc);
    return utcDate;
    //return base.GetDateTime(ordinal).ToUniversalTime();
}
like image 739
Westerlund.io Avatar asked Oct 23 '16 17:10

Westerlund.io


People also ask

What is an unspecified DateTime kind?

The DateTimeKind. Unspecified is useful in cases where you don't want the time to be converted to another local time. Take for example a server application which displays the current time for the server in a client application. If you do not specify DateTimeKind.

How do you specify the kind in DateTime?

The SpecifyKind method creates a new DateTime object using the specified kind parameter and the original time value. The returned DateTime value does not represent the same instant in time as the value parameter, and SpecifyKind is not a time zone conversion method.

What is DateTimeKind UTC?

The DateTime. SpecifyKind() method in C# is used to create a new DateTime object that has the same number of ticks as the specified DateTime but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.


1 Answers

Assuming you are using EF6 and you want to set the Kind property of any DateTime value retrieved from the database to Utc.

Similar questions have been asked, and the answers tend to suggest hooking into the ObjectContext.ObjectMaterialized event, but it didn't fire for queries that use projection.

The solution I'm going to propose works for both entity and projection queries, by performing the conversion at the DbDataReader level (which is used by this type of queries).

In order to do that, we need a custom DbDataReader implementation that intercepts the GetDateTime method. Unfortunately implementing DbDataReader derived class requires a lot of boilerplate code. Luckily I already created a base class form my answer to Dynamic Translate to avoid C# syntax errors which simply delegates each method to the underlying DbDataReader instance, so I'll just take it from there:

abstract class DelegatingDbDataReader : DbDataReader
{
    readonly DbDataReader source;
    public DelegatingDbDataReader(DbDataReader source)
    {
        this.source = source;
    }
    public override object this[string name] { get { return source[name]; } }
    public override object this[int ordinal] { get { return source[ordinal]; } }
    public override int Depth { get { return source.Depth; } }
    public override int FieldCount { get { return source.FieldCount; } }
    public override bool HasRows { get { return source.HasRows; } }
    public override bool IsClosed { get { return source.IsClosed; } }
    public override int RecordsAffected { get { return source.RecordsAffected; } }
    public override bool GetBoolean(int ordinal) { return source.GetBoolean(ordinal); }
    public override byte GetByte(int ordinal) { return source.GetByte(ordinal); }
    public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) { return source.GetBytes(ordinal, dataOffset, buffer, bufferOffset, length); }
    public override char GetChar(int ordinal) { return source.GetChar(ordinal); }
    public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) { return source.GetChars(ordinal, dataOffset, buffer, bufferOffset, length); }
    public override string GetDataTypeName(int ordinal) { return source.GetDataTypeName(ordinal); }
    public override DateTime GetDateTime(int ordinal) { return source.GetDateTime(ordinal); }
    public override decimal GetDecimal(int ordinal) { return source.GetDecimal(ordinal); }
    public override double GetDouble(int ordinal) { return source.GetDouble(ordinal); }
    public override IEnumerator GetEnumerator() { return source.GetEnumerator(); }
    public override Type GetFieldType(int ordinal) { return source.GetFieldType(ordinal); }
    public override float GetFloat(int ordinal) { return source.GetFloat(ordinal); }
    public override Guid GetGuid(int ordinal) { return source.GetGuid(ordinal); }
    public override short GetInt16(int ordinal) { return source.GetInt16(ordinal); }
    public override int GetInt32(int ordinal) { return source.GetInt32(ordinal); }
    public override long GetInt64(int ordinal) { return source.GetInt64(ordinal); }
    public override string GetName(int ordinal) { return source.GetName(ordinal); }
    public override int GetOrdinal(string name) { return source.GetOrdinal(name); }
    public override string GetString(int ordinal) { return source.GetString(ordinal); }
    public override object GetValue(int ordinal) { return source.GetValue(ordinal); }
    public override int GetValues(object[] values) { return source.GetValues(values); }
    public override bool IsDBNull(int ordinal) { return source.IsDBNull(ordinal); }
    public override bool NextResult() { return source.NextResult(); }
    public override bool Read() { return source.Read(); }
    public override void Close() { source.Close(); }
    public override T GetFieldValue<T>(int ordinal) { return source.GetFieldValue<T>(ordinal); }
    public override Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) { return source.GetFieldValueAsync<T>(ordinal, cancellationToken); }
    public override Type GetProviderSpecificFieldType(int ordinal) { return source.GetProviderSpecificFieldType(ordinal); }
    public override object GetProviderSpecificValue(int ordinal) { return source.GetProviderSpecificValue(ordinal); }
    public override int GetProviderSpecificValues(object[] values) { return source.GetProviderSpecificValues(values); }
    public override DataTable GetSchemaTable() { return source.GetSchemaTable(); }
    public override Stream GetStream(int ordinal) { return source.GetStream(ordinal); }
    public override TextReader GetTextReader(int ordinal) { return source.GetTextReader(ordinal); }
    public override Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) { return source.IsDBNullAsync(ordinal, cancellationToken); }
    public override Task<bool> ReadAsync(CancellationToken cancellationToken) { return source.ReadAsync(cancellationToken); }
    public override int VisibleFieldCount { get { return source.VisibleFieldCount; } }
}

and build the actual class that we need on top of it:

class UtcDateTimeConvertingDbDataReader : DelegatingDbDataReader
{
    public UtcDateTimeConvertingDbDataReader(DbDataReader source) : base(source) { }
    public override DateTime GetDateTime(int ordinal)
    {
        return DateTime.SpecifyKind(base.GetDateTime(ordinal), DateTimeKind.Utc);
    }
}

Once we have that, we need to plug it into EF infrastructure using EF interception.

We'll start by creating a custom DbCommandInterceptor derived class:

class UtcDateTimeConvertingDbCommandInterceptor : DbCommandInterceptor
{
    public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        base.ReaderExecuted(command, interceptionContext);
        if (!(interceptionContext.Result is UtcDateTimeConvertingDbDataReader)
            && interceptionContext.Result != null
            && interceptionContext.Exception == null)
            interceptionContext.Result = new UtcDateTimeConvertingDbDataReader(interceptionContext.Result);
    }
}

register it (for instance from your DbContext derived class static constructor):

public class YourDbContext : DbContext
{
    static YourDbContext()
    {
        DbInterception.Add(new UtcDateTimeConvertingDbCommandInterceptor());
    }
    // ...
}

and we are done.

Now every DateTime value coming from the database will have Kind property set to Utc.

like image 130
Ivan Stoev Avatar answered Oct 20 '22 04:10

Ivan Stoev