Compare two DateTimeOffset objects

I want to have a difference between two DateTimeOffset objects in days (for example, check if the difference is 40 days different).

I know this can be done by changing it to FileTime, but wondering if there is a better way to do this.

+4
source share
2 answers

The easiest way is to subtract offsets from eachother. It returns a TimeSpan with which you can compare.

 var timespan = DateTimeOffset1 - DateTimeOffset2; // timespan < TimeSpan.FromDays(40); // timespan.Days < 40 

I prefer the ability to add it to another method passing through TimeSpan, so you are not limited to days or minutes, but simply to a period of time. Sort of:

 bool IsLaterThan(DateTimeOffset first, DateTimeOffset second, TimeSpan diff){} 

For fun, if you like the free code style (I'm not a big fan of it outside of testing and tweaking)

 public static class TimeExtensions { public static TimeSpan To(this DateTimeOffset first, DateTimeOffset second) { return first - second; } public static bool IsShorterThan(this TimeSpan timeSpan, TimeSpan amount) { return timeSpan > amount; } public static bool IsLongerThan(this TimeSpan timeSpan, TimeSpan amount) { return timeSpan < amount; } } 

Allows something like:

 var startDate = DateTimeOffset.Parse("08/12/2012 12:00:00"); var now = DateTimeOffset.UtcNow; if (startDate.To(now).IsShorterThan(TimeSpan.FromDays(40))) { Console.WriteLine("Yes"); } 

Which reads something like "If the time from the start date to now is less than 40 days."

+4
source

DateTimeOffset has a Subtract statement that returns a TimeSpan :

 if((dto1 - dto2).Days < 40) { } 
+2
source

All Articles