2012-04-26 43 views
3

我有一個包含Datetimes的列表。計算2個日期時間之差(Timespan + double)

要計算我使用TimeSpan的2個日期時間之間的差異。

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; 

調試時這個代碼兩者DateTime.Nowlist[list.Count-1]具有DateTime是否其中DateTime.Now是關閉的過程更高則列表的值。

但由於某些原因,我在變量結果中一直得到0,究竟是怎麼發生的?

最好的問候,皮特

+1

這工作得很好:http://ideone.com/2FViv – mellamokb 2012-04-26 14:45:56

+1

你分配給'list'有什麼價值?在上面的代碼中,它看起來像是一樣的。 – SouthShoreAK 2012-04-26 14:47:56

回答

3

我只是嘗試了以下,完美無缺。

  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; 

附debbuging圖片:

enter image description here

理由不工作可能是:

  1. 要麼不被填充了名單
  2. 的價值或ts.TotalSeconds小於雙倍範圍(這幾乎是不可能的。)
2

首先評論,你不需要= new TimeSpan(); - 當你重新設置ts進一步下跌你只能放棄這個反正。

當您看到result的值爲0時,您的調試器開啓了哪一行?你是否已經通過行設置了result?如果你在線上,那麼該線還沒有真正運行...

+0

啊好,趕不上新:)。啊,現在似乎已經在我的if語句中意外地改變了一個值,現在值正確填充了。 – PeterP 2012-04-26 14:53:05

+0

@PeterP,David M:是的,最好是擺脫'= new TimeSpan()',但這可能不是什麼大不了的,因爲它幾乎肯定會被優化成相同的代碼,無論如何,作爲TimeSpan '是一個結構,所以無論如何它都由CLR進行零初始化。 – phoog 2012-04-26 15:01:54

1

而不是使用 ts = DateTime.Now --list [list.Count-1]; 使用 TS = DateTime.Now.Subtract(名單[list.Count-1]

1

我覺得時間差是小的幾秒鐘,它可能在毫秒或更小。嘗試蜱這樣。

結果= ts.Ticks;

1

您發佈的代碼沒有問題(除非我建議您加入變量的聲明和初始化)我必須猜測,但也許您正在「吞食」例外並通過空單?

然後行

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

將拋出異常並且result將保留它的值爲0

1

list沒有任何元素,所以list.Count - 1沒有打任何東西。另外,可能不會有整秒的計算。我添加了一個時間(使用蜱)與減去。除此之外,你所擁有的沒有任何問題。

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; 
相關問題