Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 691
Allan Jiang Avatar asked Aug 23 '12 01:08

Allan Jiang


People also ask

How to compare two DateTimeOffset c#?

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.

What is c# DateTimeOffset?

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


2 Answers

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

like image 106
Christopher Currens Avatar answered Sep 22 '22 02:09

Christopher Currens


DateTimeOffset has a Subtract operator that returns a TimeSpan:

if((dto1 - dto2).Days < 40)
{
}
like image 44
D Stanley Avatar answered Sep 22 '22 02:09

D Stanley