Question

I have a LINQ to SQL Data Context containing a class with two Date properties:

DateActive DateTime NOT NULL
DateInactive DateTime NULL

The MSDN clearly states:

The LessThanOrEqual operator determines the relationship between two DateTime values by comparing their number of ticks. Before comparing DateTime objects, make sure that the objects represent times in the same time zone. You can do this by comparing the values of their Kind property.

http://msdn.microsoft.com/en-us/library/system.datetime.op_lessthanorequal.aspx

But in my LINQ queries the two above fields are showing as DateTimeKind.Unspecified where I am comparing to Date.Today which is DateTimeKind.Local.

Is there a nice way of specifying the above properties as DateTimeKind.Local throughout the entire application so I don't have to convert like i.DateActive.ToLocalTime.Date and i.DateInactive.Value.ToLocalTime.Date everywhere?

I am using .NET 4 not .NET 4.5 so I'm presuming the same applies.

Was it helpful?

Solution

The MSDN article talks about comparing client-side dates. Linq To SQL converts your statement to SQL, where the DateTimeKind property isn't used.

You should use DateTimeOffset instead of DateTime. This will allow you to use DateTimeOffset methods in SQL and take advantage of the DATETIMEOFFSET type in SQL Server.

LINQ to SQL generates SQL statements. System.DateTime and SQL Server's DATETIME types have no timezone information so it makes no sense to try and take into account the timezone. None of the two values contain any timezone, so how can you make any automatic conversions?

The two DateTime values in your question come from two different sources. DateTime.Today comes from your local machine, where the timezone is known, so it's DateTimeKind.Local.

The database columns though come from the database, from a data type that contains no timezone info. DateTimeKind.Unspecified is the correct value here. BTW, what timezone do you assume when storing to the database? UTC? Your local timezone? Summer or winter time?

If you want to keep using the DateTime types, you will have to convert your datetime parameters to the proper timezone on the client. Comparisons between database fields do not require any conversions, as the SQL they translate to doesn't depend on the timezone.

If you want to support different timezones, you will have to switch to the DateTimeOffset types.

Of course, you can assume that all data shares the same timezone and ignore any differences, in which case DateTime is enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top