Allan Jiang
Allan Jiang

Reputation: 11331

Compare two DateTimeOffset objects

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.

Upvotes: 11

Views: 13385

Answers (2)

Christopher Currens
Christopher Currens

Reputation: 30695

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

Upvotes: 13

D Stanley
D Stanley

Reputation: 152491

DateTimeOffset has a Subtract operator that returns a TimeSpan:

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

Upvotes: 4

Related Questions