When I query a SqlServer database from C# which involves DateTime
fields, the returned System.DateTime
has Kind==Unspecified
which is unsurprising as SqlServer DateTime
type retains no timezone information.
I wondered if there's a way to automatically have these values read as local or universal, rather than manually convert them after reading the query results which introduces more possibility of mistakes when a field is missed.
Typical code looks like:
using (var conn = ...)
using (var command = ...)
{
conn.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
DateTime dateField = (DateTime)reader["date"];
//dateField.Kind == Unspecified
}
}
DateTime dateField = DateTime.SpecifyKind((DateTime)reader["date"], DateTimeKind.Utc);
As its not persisted in the database you have to specify it on retrieval in your own code, there is no shortcut method in the DataReader although you could create an Extension method.
public static class Helper{
public static DateTime GetDateTimeAsUtc(this IDataReader reader, string column){
return DateTime.SpecifyKind((DateTime)reader[column], DateTimeKind.Utc);
}
}
and then call it
DateTime dateField = reader.GetDateTimeAsUtc("date");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With