How to compare two DateTimeOffSet?

Richard77 picture Richard77 · Sep 4, 2014 · Viewed 8.1k times · Source

I have a variable which is of type DateTimeOffSet. I'd like to filter all the projectS that were created after January 1st, 2010.

So I've wrote the following query:

   var _date = new DateTimeOffset(2010, 01, 01, 0, 0, 0, new TimeSpan(-7, 0, 0));

   var projects = _repository.Find<Project>
                 (x => x.CompanyId = CompId && x.CreatedOn > _date)
                .ToList();

But when I look at the database, those are the type of values I see:

2001-01-25 05:21:46.4370000 -08:00
2005-06-17 00:00:00.0000000 -07:00

Clearly, some of the values have -08:00 and others have -07:00. So is my above query still relevant? When I look at the result, the filtering is being done the way I'm expecting it. The only concern is what the meaning of that offset part, maybe the result is good by accident.

I'm not that familiar with the way DayeTimeOffSet works.

Answer

Jon Skeet picture Jon Skeet · Sep 4, 2014

So is my above query still relevant?

Yes. When you compare two DateTimeOffset values, it's the "absolute" time that is compared. The documentation talks about this in terms of the UtcDateTime property. For example, from the op_GreaterThan documentation:

true if the UtcDateTime value of left is later than the UtcDateTime value of right; otherwise, false.

So as long as that's the behaviour you want (which I'd imagine it is), you should be fine. (Admittedly we don't know where the query is being executed - if this is LINQ to SQL or EF, then you'd be relying on that implementing the same semantics, but I think that's a reasonable expectation.)