I want to have the difference of two DateTimeOffset object in days( for example check if the difference is less than 40 days).
I know it can be done by change it to FileTime, but wondering if there is any better way of doing it.
Compare() method in C# is used to compare two DateTimeOffset objects and indicates whether the first is earlier than the second, equal to the second, or later than the second. It returns an integer value, <0 − If val1 is earlier than val2. 0 − If val1 is the same as val2.
The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC).
The easiest way would be to subtract the offsets from eachother. It returns a TimeSpan
you can compare to.
var timespan = DateTimeOffset1 - DateTimeOffset2;
// timespan < TimeSpan.FromDays(40);
// timespan.Days < 40
I tend to prefer the ability to add it to another method passing in a TimeSpan, so then you're not limited to days or minutes, but just a span of time. Something like:
bool IsLaterThan(DateTimeOffset first, DateTimeOffset second, TimeSpan diff){}
For fun, if you love fluent style code (I'm not a huge fan outside of it outside of testing and configuration)
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;
}
}
Would allow 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 start date to now is shorter than 40 days".
DateTimeOffset
has a Subtract operator that returns a TimeSpan
:
if((dto1 - dto2).Days < 40)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With