When you request DateTime fields from a database, can I control DateTimeKind?

When I query the SqlServer database from C #, which includes the fields DateTime, the returned one System.DateTimehas Kind==Unspecified, which is not surprising since the SqlServer type does DateTimenot save time zone information.

I wondered if there was a way to automatically read these values ​​as local or universal, rather than manually transforming them after reading the query results, which adds more error options when missing a field.

A typical code is as follows:

    using (var conn = ...)
    using (var command = ...)
    {
        conn.Open();
        var reader = command.ExecuteReader();
        while (reader.Read())
        {
          DateTime dateField =  (DateTime)reader["date"];
          //dateField.Kind == Unspecified
        }
    }
+4
source share
1 answer
DateTime dateField = DateTime.SpecifyKind((DateTime)reader["date"], DateTimeKind.Utc);

, , DataReader , .

public static class Helper{
    public static DateTime GetDateTimeAsUtc(this IDataReader reader, string column){
        return DateTime.SpecifyKind((DateTime)reader[column], DateTimeKind.Utc);
    }
}

DateTime dateField = reader.GetDateTimeAsUtc("date");
+4

Source: https://habr.com/ru/post/1674072/


All Articles