stack_pointer is EXTINCT
stack_pointer is EXTINCT

Reputation: 2393

How to find the positive difference between two DateTime in C#

I've two DateTime variable regardless of which is greater than the other in time.

Datetime date1, date2;

How should I find the positive difference of both on "days" basis?

(date1-date2) might give positive/negative result but I also need the no: of days difference.

Assume both are on the same TimeZone

Upvotes: 8

Views: 6739

Answers (5)

Use the subtraction operator with the TimeSpan.Duration() method.

This method returns the absolute value of the current TimeSpan object.

Sample code:

    public static int GetDayDifference(DateTime dateTime1, DateTime dateTime2)
    {
        TimeSpan diff = (dateTime1 - dateTime2).Duration();
        return diff.Days;
    }

Lets test it: Using these DateTime variables,

DateTime dateTime1 = new DateTime(2000, 1, 1);
DateTime dateTime2 = new DateTime(2000, 1, 3);

Now both of the following lines will give the same result (2 days):

GetDayDifference(dateTime1, dateTime2));
GetDayDifference(dateTime2, dateTime1));

Upvotes: 1

Steve Kennaird
Steve Kennaird

Reputation: 1674

If you want an (unsigned) integer value:

Math.Abs(date1.Subtract(date2).Days)

If you want an (unsigned) double value:

Math.Abs(date1.Subtract(date2).TotalDays)

Upvotes: 4

Simon Brydon
Simon Brydon

Reputation: 985

You could try:

Math.Abs((dateA - dateB).Days);

or if you want the result to be fractional:

Math.Abs((dateA - dateB).TotalDays);

Upvotes: 1

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171421

double days = Math.Abs((date1-date2).TotalDays);

Upvotes: 17

James Hull
James Hull

Reputation: 3689

Just use the Days property on the timespan (which is the resulting type from date1 - date2). It returns a signed int.

Upvotes: 1

Related Questions