2017-04-11 38 views
0

數據表有從日期兩米欄和兩個日期的日期時間數據類型,我需要計算兩個時間的差異我怎麼能做到這一點如何計算在asp.net兩個日期的數據表格差分C#

+0

使數據表的循環和獲取計算差異後兩個日期。你想要什麼?你想要天數差嗎? –

+0

「計算兩倍差異」,區別是什麼?你有什麼嘗試?如果你從另一個減去一個DateTime,你將得到一個你所需要的'TimeSpan'。 –

+0

差異通過從FromDate中減去ToDate來計算 – Reniuz

回答

0

您可以做這在C#這樣

DateTime dtFrom = Convert.toDateTime(aReader["fromDate"]); 
DateTime dtTo = Convert.toDateTime(aReader["ToDate"]); 
TimeSpan span = dtFrom - dtTo; 
Console.WriteLine("Difference (seconds)" + span.Seconds); 
Console.WriteLine("Difference (minutes)" + span.Minutes); 
Console.WriteLine("Difference (hours)" + span.Hours); 
Console.WriteLine("Difference (days)" + span.Days); 

在這裏看到類似的問題Showing Difference between two datetime values in hours

或者你可以制定出在SQL查詢的不同,我需要知道要連接到的數據庫類型

MySQL的

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff

MSSQL

How to compare two dates to find time difference in SQL Server 2005, date manipulation

0
  //Your Data table 
      DataTable dt = new DataTable(); 
      //Let you have following columns 
      dt.Columns.Add("Id"); 
      dt.Columns.Add("FromDate"); 
      dt.Columns.Add("ToDate"); 

     //Adding rows in data table 
     dt.Rows.Add(1, "2017-06-27T13:58:39Z", "2017-04-27T13:58:39Z"); 
     dt.Rows.Add(2, "2017-07-27T13:58:39Z", "2017-03-27T13:58:39Z"); 
     dt.Rows.Add(3, "2017-08-27T13:58:39Z", "2017-03-27T13:58:39Z"); 
     dt.Rows.Add(4, "2017-09-27T13:58:39Z", "2017-03-27T13:58:39Z"); 
     dt.Rows.Add(5, "2017-10-27T13:58:39Z", "2017-03-27T13:58:39Z"); 



     string fromDate = string.Empty; 
     string toDate = string.Empty; 
     //Looping data to get fromdate and todate value from each row 
     foreach (DataRow dr in dt.Rows) 
     { 
      fromDate = dr[1].ToString(); 
      toDate = dr[2].ToString(); 
      DateTime dtFromDate = Convert.ToDateTime(fromDate); 
      DateTime dtToDate = Convert.ToDateTime(toDate); 
      //Subtract startTimeDt from endTimeDt and get toatal seconds 
      var diffInSeconds = (dtFromDate - dtToDate).TotalSeconds; 

     } 
相關問題