Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate difference between 2 datetimes (Timespan + double)

Tags:

c#

.net

I have a list that holds 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 both the DateTime.Now and the list[list.Count-1] have DateTimes where the DateTime.Now is off course higher then the value of the list.

But for some reason i keep getting 0 in the variable result, how come exactly?

Best regards, Pete

like image 484
PeterP Avatar asked Jan 18 '26 21:01

PeterP


2 Answers

I just tried the following, works perfectly okay.

            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 the debbuging picture:

enter image description here

Reasons for not working could be:

  1. Either your list is not being populated
  2. Or the value of ts.TotalSeconds is smaller than double range (Which can be practically not possible.)
like image 90
Marshal Avatar answered Jan 21 '26 11:01

Marshal


First comment, you don't need = new TimeSpan(); - you're only discarding this anyway when you set ts again further down.

What line is your debugger on when you see the value of 0 for result? Have you stepped over the line where result is set? If you are on the line, then that line has not yet actually run...

like image 32
David M Avatar answered Jan 21 '26 12:01

David M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!