Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

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

like image 484
stack_pointer is EXTINCT Avatar asked Oct 10 '12 16:10

stack_pointer is EXTINCT


People also ask

When we subtract two dates the difference appears in what?

When you subtract two dates, you are left with a real number showing the number of days that have elapsed between the two dates.

How do I get the difference between two dates and seconds in C#?

DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20); DateTime date2 = new DateTime(2018, 7, 15, 11, 14, 25); Now calculate the difference between two dates. TimeSpan ts = date2 - date1; Move further and calculate the difference in seconds.

How do you subtract DateTime?

Subtract(DateTime) This method is used to subtract the specified date and time from this instance. Syntax: public TimeSpan Subtract (DateTime value); Return Value: This method returns a time interval that is equal to the date and time represented by this instance minus the date and time represented by value.

What is the difference between DateTime and TimeSpan?

The TimeSpan struct represents a duration of time, whereas DateTime represents a single point in time. Instances of TimeSpan can be expressed in seconds, minutes, hours, or days, and can be either negative or positive.


1 Answers

double days = Math.Abs((date1-date2).TotalDays);
like image 109
D'Arcy Rittich Avatar answered Oct 30 '22 12:10

D'Arcy Rittich