开发者

DateTime comparison, minus certain timeframe? c#

开发者 https://www.devze.com 2023-02-14 08:33 出处:网络
Say I have these two DateTime objects: var dt1 = new DateTime(1900,12,1,1,1,1); var dt2 = new DateTime(1900, 12, 1, 1, 59, 1);

Say I have these two DateTime objects:

var dt1 = new DateTime(1900,12,1,1,1,1);
var dt2 = new DateTime(1900, 12, 1, 1, 59, 1);

Obviously if I do DateTime.Compare(dt1,dt2) the method will return a value indicating they do not equal the same (because of the 59/minute component).

If I only want comparison with precision restricted to a certain value (i.e. same day - dont care about hours/minutes etc) is the best way to do this just to rebuild each datetime object?

I.e.

开发者_StackOverflow
DateTime.Compare(new DateTime(dt1.Year,dt1.Month,dt1.Day,1,1,1),new DateTime(dt2.Year,dt2.Month,dt2.Day,1,1,1))

or is there a smarter way to do this?


There is already a built in function to get the Date from a DateTime, namely the Date property:

DateTime.Compare(dt1.Date,dt2.Date)

In theory you could compare year, month and day in that order instead of building a new DateTime, but since DateTime is a small struct building it is rather cheap, causes no heap allocations etc. And the code is much more readable.


If you just want the same date, just compare the Date properties:

dt1.Date == dt2.Date

If you need down to the same hour, or up to the same month, you need to use the constructors as you've shown.


The same day is easy - just use the Date property:

dt1.Date.CompareTo(dt2.Date)

For other granularities you would probably need to manually build different values though.

0

精彩评论

暂无评论...
验证码 换一张
取 消