Calculate the difference between 2 dates (Timespan + double)

I have a list containing datetimes.

To calculate the difference between 2 DateTime i, use TimeSpan.

public static List<DateTime> list = new List<DateTime>();
TimeSpan ts = new TimeSpan();
double result = 0;

ts = DateTime.Now - list[list.Count-1];
result = ts.TotalSeconds;

When debugging this code, DateTime.Nowu list[list.Count-1]have DateTimes, where DateTime.Now is turned off higher than the list value.

But for some reason, I keep getting 0 in a variable result, how exactly?

Regards, Pete

+3
source share
6 answers

I just tried the following, it works great.

            List<DateTime> list = new List<DateTime>();
            list.Add(DateTime.Now.AddDays(-1));
            list.Add(DateTime.Now);
            list.Add(DateTime.Now.AddDays(1));
            TimeSpan ts = new TimeSpan();
            double result = 0;

            ts = DateTime.Now - list[list.Count - 1];
            result = ts.TotalSeconds;

Attached is an image for debbuging:

enter image description here

Causes of inoperability can be:

  • Or your list is not populated.
  • Or the value is ts.TotalSecondsless than a double range (which may be almost impossible).
+3
source

, = new TimeSpan(); - , ts .

, 0 result? , result? , ...

+2

   ts = DateTime.Now - list [list.Count-1];    TS = DateTime.Now.Subtract( [list.Count-1]

+1

, - , . , .

result = ts.Ticks;

+1

, ( , ). , , , "" ?

ts = DateTime.Now - list[list.Count-1];

, result 0.

+1
source
In the list

there are no elements, so list.Count - 1 doesn't hit anything. In addition, it may not take a full second to calculate. I added time (using ticks) for subtraction. Other than that, there is nothing wrong with what you have.

double result = 0;
List<DateTime> list = new List<DateTime>();
list.Add(new DateTime(123456));

TimeSpan ts = DateTime.Now - list[list.Count - 1];
result = ts.TotalSeconds;
+1
source

All Articles