2017-07-14 134 views
0

我正在計算兩次之間的差異,我得到的負值如登錄時間是「10-07-2017 09:28:00」,我正在計算與「09 :20:00「,我得到」-3.23:52:00「......我做錯了什麼?這是我的表...計算日期時間差只獲取時間期限

https://drive.google.com/file/d/0B2VzHPQzJdpmaXAxWG9KZ1o2U00/view

  string Logintime = e.Row.Cells[2].Text; 
      string Logoutime = e.Row.Cells[3].Text; 
      DateTime Logintimedt = Convert.ToDateTime(Logintime); 
      DateTime Logoutimedt = Convert.ToDateTime(Logoutime); 
      DateTime today = DateTime.Today.AddHours(09).AddMinutes(20).AddSeconds(00); 
      TimeSpan diff = (Logoutimedt - Logintimedt); 
      TimeSpan delay = today-Logintimedt; 
+0

瓦在負值的錯誤?如果你計算'「10-07-2017 09:28:00」 - 「14-07-2017 09:20:00」'否定結果是正確的! – Dmitry

+0

您確定'Logoutime'時間設置正確且不等於'DateTime.MinValue'。你能顯示Logoutime變量嗎? – Dmitry

+0

你能提供Logintime,Logouttime的價值嗎? –

回答

0

如果你需要時間差,利用DateTime.TimeOfDay

TimeSpan diff = Logoutimedt.TimeOfDay - Logintimedt.TimeOfDay; 
TimeSpan delay = Logintimedt.TimeOfDay - today.TimeOfDay; 

https://dotnetfiddle.net/9KKBfz

-1

試試這個

using System; 

public class Program 
{ 
    public static void Main() 
    { 
     string Logintime = "07-10-2017 09:28:00"; 
     string Logoutime = "07-10-2017 17:16:22 "; 
     DateTime Logintimedt = Convert.ToDateTime(Logintime); 
     DateTime Logoutimedt = Convert.ToDateTime(Logoutime); 
     DateTime today = new DateTime(Logintimedt.Year, Logintimedt.Month, Logintimedt.Day, 9, 20, 00); 
     TimeSpan diff = (Logoutimedt - Logintimedt); 
     TimeSpan delay = Logintimedt - today; 

     Console.WriteLine(diff); 
     Console.WriteLine(delay); 
    } 
}