How to compare two DateTimeOffSet?

你离开我真会死。 提交于 2020-01-03 08:47:46

问题


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.


回答1:


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.)




回答2:


DateTimeOffset maintains the offset from GMT at the time & location where the value was generated. That means that "2001-01-25 05:21:46.4370000 -08:00" was recorded in a location and a time of year (relative to DST) that was 8 hours behind GMT, while "2005-06-17 00:00:00.0000000 -07:00" was recorded at a location & time of year that was 7 hours behind GMT.

However, the timezone part is ignored when comparisons are made. In other words, each date time is converted to GMT / UTC and those are compared.



来源:https://stackoverflow.com/questions/25673103/how-to-compare-two-datetimeoffset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!